Tuesday, May 24, 2016

C#: Null Conditionals and Interpolated Strings

Two new features of C# 6.0 I've been using like crazy lately are Null Conditionals  and Interpolated Strings. These two simple pieces of syntactic sugar has made my programming life so much easier, and so I thought I'd pass the knowledge on to some of you who may not be aware of these powerful shortcuts.

Null Conditional - ?. operator MSDN

Null conditional sounds an awful lot like Null Coalescence now doesn't it? Null Conditionals work in much the same way, by first checking the value of the left side of the operator for null. First, here is an example of getting a property from an object without knowing it is null using the longhand method, then another with Null Conditionals, and finally a little trick that I'll explain below.
The above Null Conditional code with check if User is null, and, if it's not, returns the ID property. If it is null, it will simply return null. This stops the dreaded Null Exception error that we all hate to see, and makes your code much easier to read and understand!

What if you don't want null returned by the Null Conditional? Well, there's a simple trick for that as well. Combining a Null Conditional with it's cousin, Null Coalescence, you get back whatever default you want! See the third line of code above for how it's done.

String Interpolation - $"{x}" MSDN

String Interpolation is the act of injecting variables into a string without having to close the string constant and manually concatenate variables into it. An example of a traditional string concatenation is as follows:
Not too pretty, right? Here is the same example with String Interpolation.

There we go! Much easier to read! Simple to use, simple to understand, simple to read.