Over a million developers have joined DZone.

C# Null Coalescing Operator

·
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";
}
else
{
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.
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}