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;
Thanks.
It's called the null coalescing (??
) operator:
myNewValue = myValue ?? new MyValue();
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;