C# Null Coalescing Operator

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–

glyphicons Null coalescing operator can only be used in nullable or reference type. Otherwise it will raise an InvalidOperationException.

glyphicons 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.

Advertisement

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 )

Connecting to %s

%d bloggers like this: