Wednesday, November 25, 2009

C# ?? Operator

The null-coalescing operator is a great way to save space in your code.

// if ObjectThatCouldBeNull is null then print out the default text
// otherwise print the object value

if(ObjectThatCouldBeNull != null)
{
 Console.WriteLine("{0}", ObjectThatCouldBeNull);
}
else
{
 Console.WriteLine("Value is null");
}

// a better way
Console.WriteLine("{0}", ObjectThatCouldBeNull != null ? ObjectThatCouldBeNull : "Value is null");

// a even better way
Console.WriteLine("{0}", ObjectThatCouldBeNull ?? "Value is null");


sweet :-)
Share: