Null-Conditional Operator in c# 6 and above

By using C#6 we can make better visibility and reduce code line.one of the feature to handle null is shown below …

Old way to handle null
public static string getEmpName(Employee emp)
{
String result;
if (emp != null)
{
result = emp.name;
}
return result;
}

New way to handle null

public static string getEmpName(Employee emp)
{
String result;
if (emp != null)
{
result = emp?.name;
}
return result;
}

If we want to return a default value in case of null we have to use ?? Operator as below

public static string getEmpName(Employee emp)
{
String result;
if (emp != null)
{
result = emp?.name ?? “NA”;
}
return result;
}

 

Leave a comment