Tuesday, December 30, 2014

C# 6.0–Null conditional operator

This blog post is part of C# 6.0 Features Series.
As we know there are lots of small features added in C# 6.0 and Null conditional operator is one of them. You can check null with specific conditions with Null conditional operator and this will definitely increase productivity of developers and there will be less lines of code.

Let’s create example. Following are two classes I have created for this example. Address class will contains two properties like Street and City.
namespace NullConditionalOperator
{
    public class Address
    {
        public string Street { get; set; }
        public string City { get; set; }
    }
}
And Same way Person class contains four properties Id,FirstName,Lastname and Address which is of type Address class which we have created.


And following is a code of Main method of console application.
using System;

namespace NullConditionalOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person
            {
                Id = 1,
                FirstName = "Jalpesh",
                LastName = "Vadgama"
            };
            PrintAddress(person);

        }
        static void PrintAddress(Person person)
        {
            Address address = person != null  ? person.Address : null;
            if (address != null)
            {
                Console.WriteLine(address.Street);
                Console.WriteLine(address.City);
            }
        } 
    }
}
If you see above code carefully specially PrintAddress function I have used nullable operator which check the whether person is null or not and If it not null then it will return person address other wise it will return a null.

But this is a old way of doing this. Now with null conditional operator you can do same thing like below.
static void PrintAddress(Person person)
{
    //Old way of doing this.
    Address address = person?.Address;
    if (address != null)
    {
        Console.WriteLine(address.Street);
        Console.WriteLine(address.City);
    }
} 
Here you can see I have used null conditional operator. Isn’t it more readable and less code then old way.

You can download all examples  for c# 6.0 new features code from the following location on github:
https://github.com/dotnetjalps/Csharp6NewFeatures
That’s it. Hope you like it. Stay tuned for more.
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews