C# Null Coalescing Operator

DZone 's Guide to

C# Null Coalescing Operator

· ·
Free Resource
One of the coolest and little known features of C# is the null coalescing operator (??), which was added in C# 2.0.  It add some syntactical sugar to help when dealing with possible null values.  Imagine that we have some code that takes input from a user that could be coming in as null and we need to set a default if it is null.  The C# code for this may look something like this:
string val;

if(userinputstring == null)
val = "Default Value";
val = userinputstring;
This is a very longhand method of doing the check. While it can make it easier to read, you could shorten it a bit by using in inline if:
string val = (userinputstring == null) "Default Value" ? userinputstring;
The inline if is much shorter, but inline ifs can be complex and difficult to read at times.  I don't think the above example necessarily is, but I have seen them where they can be.  Using the null coalescing operator, we can shorten it even more:
string val = userinputstring ?? "Default Value";
This is certainly shorter and doesn't add as much complexity as the inline if.  What the above code is doing is checking to see if the first value is null and it if isn't, it will set the val variable to the value of userinputstring.  If userinputstring is null, then val will be set to "Default Value".  It provides a very easy way to set default values without writing a bunch of plumbing code for each item.  I first saw this concept in SQL Server with the coalesce function and loved it.  Now I get to use in C# too.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}