Blog Archives

C# 6.0 – Elvis operator and other improvements

Title

Microsoft has released yet another version of .Net framework (4.6) and C# (6.0). In this post I am highlighting few improvements released as part of C# 6.0 which will largely benefit day to day development activities of a C# developer.

Elvis operator or formally called null conditional operator (?.) makes the null check simple. In a highly hierarchical object structure this operator reduces the length of code required to check for null and proceed further.

public class Sale
{
public Order orderItem { get; set; } = new Order();
}
public class Order
{
public int orderId { get; } = 101;
}

To read the value of orderId from main() class, null checks are required on objects of two of its hierarchical structure.

Sale sale = new Sale();

if(sale != null && sale.orderItem !=null && sale.orderItem.orderId > 0)
Console.WriteLine(string.Format("In older C#, value is {0}", sale.orderItem.orderId));

if (sale?.orderItem?.orderId >0)
Console.WriteLine($"In 6.0 C#, value is {sale.orderItem.orderId}");

Elvis operator makes this simple by evaluating the above expression left to right. The expression sale?.orderItem?.orderId >0 evaluates to orderItem if the left operand sale is non-null; otherwise, it evaluates to null.

In the above class definition, you will observe the way I have initialized the properties. I have directly initialized orderItem next to the property definition and it’s called auto-property initializer. Also you will notice orderItem has only get and no setter, this feature is called get-only auto property.

Also in the above code block you will notice, first I used string.Format to format the string and latter a special and simplified template to do the same. This is again a new feature in C# 6.0 called Interpolated Strings. An interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions’ results.