C# Null Coalescing Operator

August 1, 2007

There are some new operators introduced in C#2.0. Null Coalescing operator is one of them. In many situations, we need to check like below –Contact contact = provider.GetContact(contactId);


if (contact == null)

{

contact = new
Contact();

}

Instead of using if block we could just write it –

Contact contact = provider.GetContact(contactId);
contact = contact ?? new
Contact();

It is pretty useful in case of nullable type. It can be handy while converting nullable type to value type –

int? nullableInt = null;

int valueInt = nullableInt ?? default(int);

valueInt become value type after executing this statement. But if we write something like below –

int? nullableIntAgain = nullableInt ?? 5;

5 will be automatically converted to a nullable type by CLR. We can assign it to null now –
    nullableIntAgain = null;

Isn’t pretty slick and handy? J

While using this operator we need to keep in mind that -

1.Null coalescing operator can only be used in nullable or reference type. Otherwise it will raise an InvalidOperationException.
2. We need to consider thread-safety also. Otherwise it could end up in race condition.