Search in Help for developer site.

Monday 23 April 2018

Null Conditional Operator in C Sharp 6

Null Conditional Operator New Feature in C Sharp 6.

Overview:

I focus on little things. Null check is small thing yet big.
Today i am going to share a New feature introduced in C# 6, It is called Null Conditional Operator.
While coding we need to check null to prevent any exception at run time.

I have 3 classes as follow:

    public class Vendor
    {
        public int VendorId { get; set; }
        public string CompanyName { get; set; }
        public string Email { get; set; }
    }

    public class Product
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public Vendor Vendor { get; set; }
    }

    public class Order
    {
        public long OrderId { get; set; }
        public Product Product { get; set; }
        public string GetCompanyName()
        {
            string companyName = string.Empty;
            try
            {
                //Null exception at run time
                companyName = Product.Vendor.CompanyName;
            }
            catch (Exception ex)
            {
                throw;
            }
            return companyName;
        }
    }

The GetCompanyName() Method is used to get the company name.
But it throws an exception at run time.



So we have to check null. There are two ways to check null.


Traditional way of checking null.

   public string GetCompanyName()
        {
            string companyName = string.Empty;
            try
            {
                //Null checking using If.
                if (Product != null && Product.Vendor != null)
                    companyName = Product.Vendor.CompanyName;
            }
            catch (Exception ex)
            {
                throw;
            }
            return companyName;
        }
In a large project the traditional way of checking null is a tedious task and code becomes unreadable. 

Using C Sharp 6 Null-Conditional Operator.


        public string GetCompanyName()
        {
            string companyName = string.Empty;
            try
            {
                companyName = Product?.Vendor?.CompanyName;
            }
            catch (Exception ex)
            {
                throw;
            }
            return companyName;
        }

How null operator works?.

  • If the variable on the left side is null, the expression is null.
  • If the variable on the left side is not null, then we continue with the dot.
  • "If null then null; if not then dot".
  • ?. Is the null-conditional operator.
  • Called as "Elvis operator".

Summary.

In this article i discussed about new feature introduced in C Sharp 6. Use it in your project and share your feedback in the comment section.