C# 6.0 Features Series
- How to try C# 6.0 and Rosyln?
- Getter-only (Read Only) Auto Properties in C# 6.0
- Lambda and Getter Only Auto-Properties in C# 6.0
- Initializers for Read-Only Auto Properties in C# 6.0
- Initializers via Expression Auto Properties in C# 6.0
- C# 6.0 – A field initializer cannot reference the non-static field, method, or property
- Lambda Expression for Function Members in C# 6.0
- Dictionary Initializers (Index Initializers) in C# 6.0
- Expression Bodies on Methods returning void in C# 6.0
- using keyword for static class in C# 6.0
- Unused namespaces in Different Color in Visual Studio 2015
- Null-Conditional Operator in C# 6.0
- Null-Conditional Operator and Delegates
- nameof Operator in C# 6.0
- Contextual Keywords in C#
- String Interpolation in C# 6.0
- Exception Filters in C# 6.0
- Await in Catch and finally block in C# 6.0
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