Guy MacArthur Team : Web Development Tags : Programming

My Favourite C# Operator

Guy MacArthur Team : Web Development Tags : Programming

One of my favourite C# operators I try to use at every and any opportunity is the much beloved "??" operator.  For the entirety of my life as a programmer I’ve called this little gem the “question mark question mark” operator.  And on occasion the “it means if null”, or just “is-nully” operator.  The real name for this little guy is the “null-coalescing” operator.

Here’s is is-nully in action:

string foo = null;
string bar = “Splendid”;
bar = foo ?? “Jolly Good!”;
// at this point the value of bar is Jolly Good as foo was null.

Be warned though, this conditional only evaluates as true if the object is null.  Strings can be empty OR null.  You might try the String.IsNull method when evaluating strings if empty strings are a bother.

For more C# operators and check out http://msdn.microsoft.com/en-au/library/6a71f45d.aspx