Tuesday 7 November 2017

Null-Conditional Operator in C# 6.0

Null-Conditional Operator is a new Concept in C# 6.0 that is useful when we want to check the null condition of an object or reference data type.  We can write an in-line null-conditional with the ? and ?? operators.
Syntax:
                Condition ? if true ?? if false
Example:-
namespace ConsoleApplication2
{
    class Program
    {
        class Employee
        {
            public string Name { getset; }
            public Address EmpAddress { getset; }
        }

        class Address
        {
            public string HomeAddress { getset; }
            public string OfficeAddress { getset; }
        }
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.Name = "Max";
            emp.EmpAddress = new Address()
            {
                HomeAddress = "Street",
                OfficeAddress = "Street1"
            };
            Console.WriteLine(emp?.Name);
            Console.WriteLine((emp?.EmpAddress ?.HomeAddress ?? "Nothing"));
            Console.ReadLine();
        }
    }
}

In the above example I created 2 class and which contain Some of the Properties and in the main method we assign the value to those properties. However, in this Statement,
Console.WriteLine(emp?.Name);
It will show Employee Name if it is not null.
Console.WriteLine((emp?.EmpAddress ?.HomeAddress ?? "Nothing"));

In the above Statement  if emp?.EmpAddress is not null then it will access HomeAddress else it will Show “Nothing “ in EmpAddress.

0 comments:

Post a Comment