Null-Conditional Operator in C# 6.0

C# 6.0 Features Series

One of the new operator introduced with C# 6.0 is the Null-Conditional operator . With the earlier versions of C# , you might have to use the if condition to check if the object is not null and perform certain set of actions based on it .

For example , assume a scenario where you have an Employee Object as shown below.

public class Employee
{
    public int ID { get;}
    public string LastName { get; set; } = "Kumar";
    public string FirstName { get; set; } = "Senthil";
    public string Name  => FirstName + LastName;
}

In order to retrieve the name of the employee , you might want to check if the employee object is not null and then retrieve the value.

public class EmployeeHelper
{
    public void GetEmployee()
    {
        Employee emp=null;
        if (emp != null)
        {
            var Name = emp.Name;
            Console.WriteLine(Name);
        }
    } 

}

Alternatively , you could use the ternary operator as well.

With C# 6.0 , this null check can be simplified further with the ?. operator.

public class EmployeeHelper
{
    public void GetEmployee()
    {
        Employee emp=null;
        var Name = emp?.Name;
        Console.WriteLine(Name);       
    } 

}

The null conditional operator lets the developers to access the members only when the left hand side is not null . it exhibits a kind of short circuiting behaviour where the immediate member access will be executed if the receiver was NOT null.

No Responses

Leave a Reply