Blog

Blogging on programming and life in general.

C# NULL Coalescing Operator

Posted in: C#

Here is a really neat trick that a mate showed me at work. It is a way to assign one variable to another, but only if the variable is not null. If it is null, you want to populate the target variable with perhaps another value.

For example, lets assume we have an integer variable "intCounter". We could check if the integer contents was null, and if not return another value: 

int intCounter = 5;
int intResult = intCounter ?? 0;
// Output: intResult == 5 

We got the following output because intCounter did not contain a null.

The C# NULL coalescing operator also works with string variables as well:

string strMessage = "Hello World";
string strResult = strMessage ?? "No message";
// Output: strResult == "Hello World" 
So we can see from the two examples above that this NULL Coalescing operator is quite useful. Here is an example of what would have happened if a variable was null:
string strMessage = null;
string strResult = strMessage ?? "No message";
// Output: strResult == "No message" 

Scott Guthrie talks more about this in his own blog and how to use this feature in LINQ: http://weblogs.asp.net/scottgu/archive/2007/09/20/the-new-c-null-coalescing-operator-and-using-it-with-linq.aspx

blog comments powered by Disqus
;