Click here to Skip to main content
15,881,248 members
Articles / Programming Languages / C#

How to Use Null-Coalescing Operator (??)

Rate me:
Please Sign up or sign in to vote.
4.73/5 (7 votes)
29 Aug 2013CPOL1 min read 49.6K   10   9
How to Use Null-Coalescing Operator

Introduction

  • The ?? operator is called the null-coalescing operator
  • It's used to define a default value for nullable value types or reference types
  • It returns the left-hand operand if the operand is not null
  • Otherwise it returns the right operand

Null-Coalescing Operator

Compile-Time Errors and Exceptions

  • A nullable type can contain a value, or it can be undefined
  • The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type
  • If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error

It's like this

C#
int? x = null;//x is nullable value type
int z = 0;//z is non-nullable value type
C#
z = x; 

Cannot implicitly convert type 'int?' to 'int'.

But if you use ?? operator. You won't have any problem.

C#
z = x ?? 1;//with ?? operator No issues 
  • If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown

It's like this

C#
int? x = null;//x is nullable value type
int z = 0;//z is non-nullable value type
C#
z = (int)x;//when you run the app,
           //It'll give ==>

Nullable object must have a value

But If you use ?? operator, you won't have any problem.

C#
z = x ?? 1;//with ?? operator No issues
  • The result of a ?? operator is not considered to be a constant even if both its arguments are constants

Example

C#
class Program
    {
        static void Main(string[] args)
        {
            //EXAMPLE 01 :    

            int? x = null;
            // y = x, unless x is null, in which case y = -1

            int y = x ?? -1;

 
            //EXAMPLE 02 : ?? Operator With Value Type

            // Assign i to return value of method, unless
            // return value is null, in which case assign
            // default value of int to i

            int i = GetNullableInt() ?? default(int);

 
            //EXAMPLE 03 : ?? Operator With Reference Type

            string s = GetStringValue();

            // Assign content of s to z, unless s is null, 
            // in which case assign "Unspecified"

            var z = s ?? "Unspecified";
        }

        static int? GetNullableInt()
        {
            return null;
        }

        static string GetStringValue()
        {
            return null;
        }
    }

Output

Example 01

Null-Coalescing Operator Example  1

Example 02

Null-Coalescing Operator Example  2

Example 03

Null-Coalescing Operator Example  3

Usage of ?? Operator

  • The chaining is a big plus for the ?? operator. It removes a bunch of redundant IFs

    e.g.

    C#
    string finalVal = parm1 ?? localDefault ?? globalDefault; 
  • You can easily convert nullable value types into non-nullable types

    e.g.

    C#
    int? test = null;
    var result = test ?? 0; //now the result is int, not nullable int?
  • You can use null-coalescing operator in lazy instantiated private variables

    e.g.

    C#
    private IList<Car> _car;
    
    public ILis<Car> CarList
     {
       get { return _car ?? (_car = new List<Car>()); }
     }

References

?? Operator

Conclusion

  • It can greatly enhance your code, making it concise and pleasant to read.
  • Enjoy this ?? operator and let me know if you have any issues.

I hope this helps you. Comments and feedback are greatly appreciated.

You Might Also Like

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Freelancer
Sri Lanka Sri Lanka
Sampath Lokuge holds a Bachelor of Science degree in the Mathematics and Computer Science at the University of Colombo, Sri Lanka.

He possesses over 8 years of experience in constructing web applications using Microsoft Technologies including ASP.net MVC, C#, SQL Server, Web API, Entity Framework and also other web technologies such as HTML5, CSS3,jQuery and AngularJS.

Sampath has earned Microsoft certifications such as MCP, MCAD, MCSD and MCTS and very recently he has completed MS (Microsoft Specialist) for MVC 4 and MCSD (Windows Store Apps Using HTML5).

Besides that, he is an active blogger, writing about web and mobile development issues and promoting best practices.He also actively participates in online communities such as Code Project and StackOverflow.He himself is handling three communities, which are ASP.net MVC 5 With C# on Linkedin,Entity Framework 6 on G+ and Hybrid Mobile App with WinJS on Facebook.

Now, I am a 100% Freelancer. Smile | :)

Tech Blogs


Sampath Lokuge Tech Universe

Communities which I'm Handling :


Entity Framework 6

ASP.net MVC 5 With C#

Hybrid Mobile App with WinJS

Comments and Discussions

 
SuggestionCan lead to messy code.. Pin
User 1013254630-Aug-13 1:23
User 1013254630-Aug-13 1:23 
GeneralRe: Can lead to messy code.. Pin
Sampath Lokuge30-Aug-13 6:24
Sampath Lokuge30-Aug-13 6:24 
GeneralMy vote of 5 Pin
Volynsky Alex30-Aug-13 0:25
professionalVolynsky Alex30-Aug-13 0:25 
GeneralRe: My vote of 5 Pin
Sampath Lokuge30-Aug-13 0:42
Sampath Lokuge30-Aug-13 0:42 
GeneralRe: My vote of 5 Pin
Volynsky Alex30-Aug-13 1:36
professionalVolynsky Alex30-Aug-13 1:36 
SuggestionNeed to fix the title Pin
Brad Bruce29-Aug-13 0:16
Brad Bruce29-Aug-13 0:16 
GeneralRe: Need to fix the title Pin
Sampath Lokuge29-Aug-13 0:29
Sampath Lokuge29-Aug-13 0:29 
GeneralRe: Need to fix the title Pin
Brad Bruce29-Aug-13 1:40
Brad Bruce29-Aug-13 1:40 
GeneralRe: Need to fix the title Pin
Sampath Lokuge29-Aug-13 3:36
Sampath Lokuge29-Aug-13 3:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.