Published on

C# - 6.0 Null Conditional Operator

Before C# 6

static void Main( string[ ] args )
{
    Employee emp = null;
    if(emp != null)
    {
        Console.WriteLine( emp.EmpName );
    }
}

class Employee
{
    public string EmpName;
}

C# 6

static void Main( string[ ] args )
{
    Employee emp = null;
    Console.WriteLine( emp?.EmpName );
}

class Employee
{
    public string EmpName;
}

Before C# 6

static void Main( string[ ] args )
{
    Employee emp = null;
    var name = emp != null ? emp.EmpName : "NoName";
    Console.WriteLine( name );
}

class Employee
{
    public string EmpName;
}

C# 6

static void Main( string[ ] args )
{
    Employee emp = null;
    var name = emp?.EmpName ?? "NoName";
    Console.WriteLine( name );
}

class Employee
{
    public string EmpName;
}