Few new operators have been introduced in C#2.0. Null Coalescing operator, which is one of them, is discussed in this post. While coding, we frequently need to perform null checks as follows–
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 the context of nullable types. It can also be handy while converting nullable type to value type, as shown below–
int? nullableInt = null; int valueInt = nullableInt ?? default(int);
The valueInt become value type after executing this statement. But if we write something like this–
int? nullableIntAgain = nullableInt ?? 5;
the int literal 5 is automatically converted to a nullable type by CLR and afterwards, being assigned to nullableIntAgain. Subsequently, we can assign it to null now–
nullableIntAgain = null;
Isn’t pretty slick and handy? However, when using this operator we need to keep in mind that–
We need to consider thread-safety also. Otherwise it could end up in race condition.
Hope it helps. Thanks!
Revisions
[R-1: 29-03-2013] Updated formatting to make this post more consistent with current CSS.