The C# Null-Coalescing Operator ??

C-based languages have several cool short-hand operators that allow you to perform inline operations that might otherwise take 3-10 lines of code. Ternary expressions are a classic example of this sort of thing that exist is most languages, allowing users to do simple if/else values inline. For example, in C# you might have some logic that looks like this:

[sourcecode language=”csharp”]int myInt = 42;
string myResult = "";

//normal value assignment
if (myInt > 0)
{
myResult = "myInt is positive.";
}
else
{
myResult = "myInt is not positive.";
}[/sourcecode]

which could be simplified to:

[sourcecode language=”csharp”]int myInt = 42;

//ternary value assignment
string myResult = (myInt > 0) ? "myInt is positive."
: "myInt is not positive.";[/sourcecode]

In C#, ternary expressions can be used just about anywhere—though you may need to wrap the whole thing in another set of parentheses 🙂

Recently I discovered the null-coalescing operator in C#: ?? The null-coalescing operator allows you to check if a variable has a null value and on-the-fly provide a default value in its place. An example for this would be:

[sourcecode language=”csharp”]int? myInt = null;

//do some input and processing…

//normal null checking
if (myInt == null)
{
return 0;
}
else
{
return myInt;
}[/sourcecode]

which could be simplified to:

[sourcecode language=”csharp”]int? myInt = null;

//do some input and processing…

//null-coalescing
return (myInt ?? 0);[/sourcecode]

I have found this operator to be extremely useful in setting up SQL statements where “null” parameters require a particular database constant, as well as for checking uninitialized object members.

Tagged with: , , , ,
Posted in Blurbs