Wednesday, October 18, 2017

Null Coalescing Operator

Remember this operator from your first Perl class back in 1994?  Well, if you don't it's a good one for your back pocket.  It works in Perl, Bash, C#, F#, Objective-C, Swift, and even SQL.  It is great for a quick way to do a Null comparison:

string strNewValue = strRequestValue ?? "Default";

In this case, if strRequestValue is null, "Default" is assigned to strNewValue.

In SQL Server, it looks like this:

ISNULL(strRequestValue, 'Default')
Neither of these formats are super readable unless you are used to seeing them.  In the case of the SQL example, it looks very close to the IS NULL comparison, but whatever => the SQL team at MSFT sometimes does things like that.

It might be you want to do this instead:

string strNewValue = isNullOrEmpty(strRequestValue) ? "Default", strRequestValue;

but I never found this to be very readable either.

I think the real power of Null Coalescing Operators is when it's used to create an object instance like this:

private IList<Foo> _foo;
public IList<Foo> ListOfFoo
             { get { return _foo ?? (_foo = new List<Foo>()); } }
Boom!  You're off an running!

(Props go to @wilbursullivan who showed me this)

No comments:

Post a Comment