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


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;


11/14/2011 7:58:15 AM

Accepted Answer

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

myNewValue = myValue ?? new MyValue();
9/27/2011 2:53:18 PM

Sadly, there's no equivalent to the null coalescing operator that works with DBNull; for that, you need to use the ternary operator:

newValue = (oldValue is DBNull) ? null : oldValue;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow