C# 6.0 brought a set of most useful features with Visual Studio 2015 Preview and .NET 4.6. If you didn’t yet explore the features, check out the embedded links within this post to learn what’s coming with it. Download the preview to get your hands dirty before you use in production.
Today in this blog post, we will discuss about a new feature called “null-conditional operators”, which will actually improve your productivity. Let’s start with it.
Don’t forget to read my previous posts on this series:
“Null-conditional operators” – a new feature introduced by Microsoft CSharp Team in C# 6.0 will definitely improve the productivity of the developers by reducing lines of code. Not only this, it may also reduce the possible no. of bugs in code keeping the code clean.
Like nullable types, null-conditional operators can be used now. Just put a ‘?’ (question mark) after the instance before calling the property on top of it. You don’t have to write additional if statements to check for null now. For example, let’s see a simple if condition which we will then see with the null-conditional operator in C# 6.0:
In the above code snippet, you can see how the Null-conditional operator (“?.”) can be used to reduce the no. of lines in code file and provide an easy access to check for Null and return the result. Here, it will return the address only if the instance of Employee object is NOT Null. Otherwise, it will just return a simple null value.
You can even add more if conditions to create a nested if statements. To begin with, let’s take a simple nested if statement which we will then convert to ternary operator and then reduce it more to leverage the C# 6.0 feature:
In the above code snippet you can see, how C# 6.0 provides the way to check for Null and return you the actual value if it satisfies all the cases. And that’s all in a simple way. Reduction of lines, reduction of efforts… reduction of bugs and/or NullReferenceException (only if the developer utilizes it).
Now let’s see, how it can be used to return a default value if the condition does not satisfy at all. In the below code snippet, you can see that “??” conditional operator can be used along with the null-conditional operator to return a value. In this case, if either of emp (employee object) or MemberOfGroups value is null, it will return –1:
Isn’t it so simple and a very good feature in C# 6.0? How much did you like it? Please drop a line below and share your feedback with the other developers. We would be happy to hear your favorite C# 6.0 feature. If I haven’t already cover that yet, will surely post it here.
Don’t forget to subscribe my blog’s RSS feed and Email Newsletter to get new article updates directly deliver to your inbox. I am also available on Twitter, Facebook and Google+. Connect with me there to get the regular updates on what I share to the community.CodeProject