C# equivalent of the IsNull() function in SQL Server

HAdes picture HAdes · Oct 4, 2008 · Viewed 186.6k times · Source

In SQL Server you can use the IsNull() function to check if a value is null, and if it is, return another value. Now I am wondering if there is anything similar in C#.

For example, I want to do something like:

myNewValue = IsNull(myValue, new MyValue());

instead of:

if (myValue == null)
  myValue = new MyValue();
myNewValue = myValue;

Thanks.

Answer

Kent Boogaart picture Kent Boogaart · Oct 4, 2008

It's called the null coalescing (??) operator:

myNewValue = myValue ?? new MyValue();