Code Mahek
  • Blog
  • About
  • Contact
  • Random Clicks
  • Resume
  • Ava Chat Bot

Fragrance
​of Programming

C# 6.0 New Features - Null Conditional Operators

4/8/2015

Comments

 
C# 6.0 includes a set of useful features with Visual Studio 2015 Preview and .NET 4.6. In my previous post I had explored "nameof" expression and how to assign the default values to the Auto-Properties.

Today in this post, we will discuss about a new feature called "Null Conditional Operators" that is really very handy, will improve your productivity, and may also reduce the potential bugs.

Developer can now use the null-conditional operator same way they use the null-types. Developer just have to include "?" after the instance and before calling the property on top of it. He doesn't have to include the null validation code. Below is the example.
Picture
Code without Null Conditional Operator
Picture
Code with Null Conditional Operator
From the above code you can see how null conditional operator reduces the no. of lines in the code and provides an easy and clean way to check for the NULL validation and even reduces the potential bugs. In the above "WardName" will be returned only if the Instance of "Bed" is not null, else it will return a simple null value.

Developer can even add more if condition to create a nested if statements. Below is the example.
Picture
Nested Null-Conditional Operator
From the above code snippet you can see how Null Conditional operator validates for the NULL and returns the value. And you can actually see how much less code Developer needs to write and with less potential bugs.

Now we will see how we can return the Default value if none of the condition is satisfied. Here we can use "??" operator to assign the default value along with Null Conditional operator. Below is the example.
Picture
Default Value with Null Conditional Operator
With all the above example of Null Conditional Operator you can see how useful this feature is for Developer. Please share your feedback if any and also share this post with your fellow Developers. Happy Coding.

Rishi
Comments
comments powered by Disqus

    RSS Feed

    Categories

    All
    Azure
    C#
    Cloud
    CodeProject
    CSharp
    DotNet Core
    Jetbrains
    .NET
    Rider
    Source Generators
    SQL
    Tech News
    Ubuntu
    Visual Studio 2015
    Visual Studio 2019
    Windows
    Windows 10

    Archives

    May 2020
    February 2019
    January 2019
    December 2018
    May 2018
    December 2017
    November 2017
    October 2017
    September 2017
    July 2017
    May 2017
    April 2017
    May 2015
    April 2015
    March 2015

    View my profile on LinkedIn

Location

Contact Us

    Subscribe Today!

Submit
  • Blog
  • About
  • Contact
  • Random Clicks
  • Resume
  • Ava Chat Bot