I don't think that it's much of a secret that I am a total code nerd! No more so is this true than when it comes to efficient, readable, bug-free, well-structured object oriented goodness - especially in the oh-so elegant form of C#. With that in mind, there are many incredibly cool features coming in C# 6.0 that Sean Sexton has already done a brilliant job of blogging about in bitesize fashion here.
Since Sean really has done such a fantastic job already, I will only be delving into one feature in this post. If the title didn't give it away, it's the Null-propagating operator!
You'll probably be used to seeing question mark used in the following ways:
- ?? (null coalesce operator)
- ?: (conditional operator)
- T? (shorthand for Nullable<T>)
Well, in C# 6.0, you'll be seeing it used like this too:
Any programmer that has experienced a Null Reference Exception will know that a fair few lines of code go into the frequent act of null-checking your references before making member calls on them. Here's an example of calling ToString() on a child's child's child when any one of them could be Null. It's a contrived example, but there are a lot of real world scenarios that are just as bad.
public string ChildChildChildToString(Parent parent) { if (parent == null) return null; if (parent.Child == null) return null; if (parent.Child.Child == null) return null; if (parent.Child.Child.Child == null) return null; return parent.Child.Child.Child.ToString(); }
Phew! That's 11 lines, without curly braces, just to say return null if this step is null. For completeness sake, here's the same example, this time using the already available conditional operator to try and thin it down a bit.
public string ChildChildChildToString(Parent parent) { return parent == null ? null : (parent.Child == null ? null : (parent.Child.Child == null ? null : (parent.Child.Child.Child == null ? null : parent.Child.Child.Child.ToString()))); }
Argh, my fingers! And my eyes! Ok, so it may not be that bad, but there's a lot of repeated typing there just to check for null and those five lines of code are not exactly easy to read. Let's not forget either that we're having to do this absolutely everywhere that there's the potential for a reference to be null (which is pretty much everywhere anything remotely complex is going on).
And now, for the moment you've been waiting for. Here's the same example, but this time using the planned null-propagating operator.
public string ChildChildChildToString(Parent parent) { return parent?.Child?.Child?.Child?.ToString(); }
Even just typing that made me want the feature right now! It's easy to read, quick to type, doesn't spam up my screen with null-checking and just plain makes sense. Love it.
No comments:
Post a Comment