views:

11079

answers:

5

In sql server you can use the IsNull funtion to check if a value is null. I am wondering if there is anything similar in C#, rather than manually checking:

For eg:

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

instead of:

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

Thanks.

+30  A: 

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

myNewValue = myValue ?? new MyValue();

HTH, Kent

Kent Boogaart
Very nice, thanks.
HAdes
That's one of my favorite C# features...very terse.
Codewerks
+5  A: 

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;
Robert Rossney
Nitpick: I know lots of places refer to this as the ternary operator. There happens to only be one ternary operator at the moment, but that's a property of it, not its name. It's really the conditional operator. If C# ever gains another ternary operator, there'll be a lot of confusing books.
Jon Skeet
A: 

For working with DB Nulls, I created a bunch for my VB applications. I call them Cxxx2 as they are similar to VB's built-in Cxxx functions.

You can see them in my CLR Extensions project

http://www.codeplex.com/ClrExtensions/SourceControl/FileView.aspx?itemId=363867&changeSetId=17967

Jonathan Allen
A: 

This is meant half as a joke, since the question is kinda silly.

public static bool IsNull (this System.Object o)
{
   return (o == null);
}

This is an extension method, however it extends System.Object, so every object you use now has an IsNull() method.

Then you can save tons of code by doing:

if (foo.IsNull())

instead of the super lame:

if (foo == null)
FlySwat
This does not answer the question.
spoon16
Why do you think the question is silly Jonathan?
HAdes
A: 

Very helpful post.

Nursing home