03.Feb.15

Vladimir Milev

Vladimir Milev

A practical analysis of the new features of C# 6: Part 1

I have been writing .NET code for more than 10 years now and have been using the C# language ever since it's first original version. It should come as no surprise then, that major updates to the language have always been big news for me as it is something that will profoundly change the way I work. I bet the same goes for many other fellow C# developers as well. We have all been there: C# 2.0 introduced anonymous methods and generics, version 3.0 added LINQ, implicit typing and initializers then it was in 4.0 when we got dynamic binding and optional parameters to the current fifth version when we have exciting new support for asynchronous programming. While this is not a complete list of all the changes, I think we can all agree that each major new version of the language changed the way we write our code. The evolution of C# allowed us to write more elegant and streamlined code, to be more productive, and to generally do more with less. This trend in language evolution continues with the newest implementation of C# - version 6. While it is still in preview phase there is quite a bit of information about it already. I am using the January 16 CTP5 preview build for writing this blog post. Some of the features may be dropped from the final release and new ones included so don't treat this article as a "final definitive guide to C# 6", as it isn't. Also note that there are many articles listing what's new in C# 6 already. My goal with this blog post is not to simply repeat that information, but rather to try and give you my perspective and analysis on the meaning of those features and how I see them affecting our daily work as developers. So let's get started!

Better initializers

This is a major theme throughout all improvements in C# 6. Initialization and member access will require significantly less code and our code will be much more elegant. Let's take a look at some of the improvements:

Automatic Property Initializers

Automatic properties were first introduced in C# 3 and now they are receiving yet another upgrade! Let's take a look at their evolution.

C# 1.0

This is the initial version of the language. Here we had to manually declare our backing field.
private Guid objectId = Guid.NewGuid();

public Guid ObjectId
{
	get
	{
		return this.objectId;
	}
	private set
	{
		this.objectId = value;
	}
}

 C# 3.0

This version introduced the first major upgrade - automatic properties where the compiler takes care of the backing field declaration:
public Guid ObjectId { get; private set; }
Much simpler already, isn't it? However, we've lost our GUID initialization and now the value defaults to "{00000000-0000-0000-0000-000000000000}". If we want to use the new automatic property syntax we are required to initialize it in a method or a constructor somewhere else. This is what this usually looks like when done in the default constructor:
public Program()
{
	this.ObjectId = Guid.NewGuid();
}
But what if we want to use BOTH the elegance of the auto property syntax and the cohesion that inline initialization in 1.0 offers? I mean we can do this with fields, why not with properties? Why not indeed! In C# 6.0 we can! The whole thing is now a one liner. Quite elegant indeed:

C# 6.0

public Guid ObjectId { get; private set; } = Guid.NewGuid();

Analysis

This change will affect developers in more ways than just saving them from writing a bit more code. The cohesiveness of having the initialization right next to the declaration of the property ensures that we don't "forget" about its existence. Sure, the compiler will issue an error about that line in the constructor if you delete or change the property, however, it will not give you a warning if you accidentally remove your initialization. This syntax will make your code more readable and will let you spot potential problems more easily. Btw, to further cover this case you can and you SHOULD write a unit test which checks for proper initialization ;-)

Indexed member initialization

There are also some new improvements with regards to indexed members initialization. The most typical example of an indexed member is the Dictionary<Tkey, TValue>. Let us consider the following C# 3.0 code which makes use of collection initializers to populate the dictionary:

C# 3.0

var englishBulgarianDict = new Dictionary<string, string>()
{
	{ "apple", "ябълка" },
	{ "tomato", "домат" },
	{ "water", "вода" }
};
This initialization works because the Dictionary class implements the IEnumerable interface and contains an Add method (ICollection is actually not required!). When the add method accepts two parameters such as key/value in our case, the rule is to simply enclose them together in curly braces. Meet the new syntax:

C# 6.0

var englishBulgarianDict = new Dictionary<string, string>()
{
	["apple"] = "ябълка",
	["tomato"] = "домат",
	["water"] = "вода"
};

 Analysis

There are several angles to this change from my perspective. They are mainly about readability and expressiveness of the language. Such features are often designated the "syntactic sugar" label. Still, it doesn't mean they are pointless. On the contrary - by reading the code above you immediately get that: 1) you are dealing with an indexed member. You may think this is not a big deal - after all we all know that the dictionary class is indexed right? It is so, but this syntax is still really useful for custom/user created classes for which this behavior is not otherwise known or immediately evident. 2) The direction of the assignment is immediately and unambiguously obvious. There is simply no way to mistake which one is the key and which one is the value with this syntax. So this one is mostly readability and expressiveness which is still a very nice addition and arguably improves the language quite a bit.

$ operator

I think the $ operator deserves a special note in this section as well. In earlier preview releases when it was available it provided you with the ability to invoke string type indexed properties like this:
var englishBulgarianDict = new Dictionary<string, string>()
{
	$apple = "ябълка",
	$tomato = "домат",
	$water = "вода"
};

var bulgarianForTomato = englishBulgarianDict.$tomato;
Because of the nature of JSON and XML it is quite common to have indexed object keys be strings. It would have made working with these very common objects more streamlined, however, this feature is currently no longer available in the newest previews and is not expected to be part of the final release of C# 6.0 This wraps up my analysis of the first two major features of C# 6.0 I would love to hear you opinions on the matter and discuss what you think are the benefits and uses of these new language improvements. To be continued in part 2

If you found this article useful, could you hit any of the share buttons below, so that others can benefit from it, too? Thanks!

Need consulting on this topic?

Yes No

Thank You! We will be in touch.