Menu

Null Coalescing Operator

December 13, 2012 - Programming

Another quick post about a C# language feature. The Null coalescing operator.
/p>

The Idea of null is a simple one that is still argued as being either the root of programming evil or a necessary one. But this is no time to wax about the philosophy, or who was right and who was wrong about language designs that involve the ability to have undefined values, because either way, we have to deal with them.
/p>

NullPointerExceptions (Java) and NullReferenceExceptions(C#) are the errors that make everybody squeal with rage. The reason is that they are typically quite simple to guard against. one common pattern is code not unlike the following:

/p>

Basically, if the parameter is null, it uses some default value; this is used quite prominently particularly when dealing with overloads being used for optional arguments. (Optional being a capability added in C# 4.0, but it has some caveats that are out of the scope of this post). The Null coalescing operator basically works for this instance:

/p>

The basic idea is relatively simple- if the first operand is null, it returns the second operand. otherwise it returns the first operand. Another way to look at it is that it returns the first of the operands that is not null. In the above example, it didn’t save a huge amount of code, but it can really simplify logic sometimes. An example can be found in BASeBlock. To quickly explain, BASeBlock is an arkanoid clone with various types of blocks that have different effects on the game. In this specific instance, a Block called “ReplacerBlock” replaces one type of Block in the level with another wherever they occur. The example usage occurs in a property:

SearchBlockType is the Type of Block to search for. in this case the property is the string name of the Block type to find, rather than the type itself. I did it this way to make it easier to edit via the editor. Anyway, since the replacer sort of needs an actual Type, it has to turn it into one. The result here is that if the set type is not a valid type (retrieveType() returns null if that is the case) it will remain unchanged. An argument could probably be made that this is bad design, and I agree, but at the same time my point is that the null coalescing operator… uhh… coalesced… the code to be smaller.
/p>

C# is of course not the only language with this capability; Perl has the operator, as //. it’s a very powerful and interesting operator that can replace the ternary operator in some contexts.

Have something to say about this post? Comment!