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.

    1 Comment

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...