C# NULL Coalescing Operator

Published on
-
1 min read

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

Tags:
Categories:C#

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself.