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.

Advertisements

About Krishnaraj Barvathaya

I am Krishnaraj Barvathaya, a software developer from Bangalore and I primarily write on Microsoft Technologies and latest technical stuffs which interests me.

Posted on September 26, 2015, in .Net and tagged , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: