Monday, November 3, 2008

Remembering NULL-Coalescing operator

It's A clean and smart operator to deal with null values to make a
decision on them. Nullable types since .NET 2.0 brought opportunity
to work with value type which can be null too. To make a value type
"Nullable" we can add a ? follwoing the type like:
...
int? height = null;
...
Well now that we have nullable types, we can check null value and use
Coalesce Operator for a conditional assignment. ?? means if left side is
null, then give the right side value.

The ?? operator returns the left-hand operand if it is not null, or else it
returns the right operand.
...
string firstName = this.getFirstName();
Console.WriteLine( firstName ?? "No name" );
...
?? operator is also protecting it. It makes us able to assign a nullable type
to a non-nullable type with correcting the value if its null.
...
int? i = null;
int x = i ?? -1; // x = -1
...
string txtMsg = null;
string outMsg = txtMsg ?? "Hello world!"; // outMsg = "Hello world!"
...

?? is the same as ISNULL in Transact-SQL which implemented
in .NET but it's not popular between developers.
ISNULL ( check_expression, replacement_value )
Share/Bookmark