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.

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

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

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

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

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

It’s like this

int? x = null;//x is nullable value type
int z = 0;//z is non-nullable value type
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.

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

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;
        }
    }

Usage of ?? Operator

  • The chaining is a big plus for the ?? operator. It removes a bunch of redundant IFse.g.
    string finalVal = parm1 ?? localDefault ?? globalDefault;
  • You can easily convert nullable value types into non-nullable typese.g.
    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 variablese.g.
    private IList<Car> _car;
    
    public ILis<Car> CarList
     {
       get { return _car ?? (_car = new List<Car>()); }
     }
Advertisements
By Sriramjithendra Posted in C#.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s