dev csharp

In current C# a collection initialization can be done like this:

var result = new Dictionary<string, string>();
result.Add("index1", "value1");
result.Add("index2", "value2");

or key - value pairs can be added during initialization

var result = new Dictionary<string, string>() 
{
	{"index1", "value1"},
	{"index2", "value2"}
};

With C# 6.0 values at specific indices can be initialized like this:

var result = new Dictionary<string, string>() 
{
	["index1"] = "value1",
	["index2"] = "value2"
};

It’s a shorthand but not so much! I don’t see much value in this notation but I’m sure in time it will prove itself. I don’t think the guys in the language team are just adding random features!

dev csharp

One of favorite features is the new string formatting using String Interpolation. In the past I encountered a lot of errors while formatting strings especially when preparing log messages. You may need lots of small pieces of data that so after a few iterations you may forget to add new parameters.

For example in the imaginary Log method below only 3 parameters are supplied whereas the string expects 4. It compiles successfully because the string is generated at run-time and it doesn’t check the number curly braces against the number of parameters supplied.

Argument count mismatch error

Using the new feature such errors can be avoided as we can put the values directly in their places in the string:

public class StringInterpolation
{
    public string Log(string timestamp, string application, string error, string status)
    {
        return string.Format("[Timestamp: \{timestamp}], Application: [\{application}], Error: [\{error}], Status [\{status}]");
    }
}

No more parameter mismatch errors!

dev csharp

It’s a shorthand for writing methods. The body now can be written just like a Lambda expression as shown in Log2 method below:

public string Log(string timestamp, string application, string error, string status)
{
    return string.Format("[Timestamp: \{timestamp}], Application: [\{application}], Error: [\{error}], Status [\{status}]");
}

public string Log2(string timestamp, string application, string error, string status) => string.Format("[Timestamp: \{timestamp}], Application: [\{application}], Error: [\{error}], Status [\{status}]");

It may come in handy for helper methods. The only benefit I can see is getting rid of opening and closing curly braces which generally don’t bother me much. But I know lots of people trying to avoid curly braces as much as possible. I’m sure this feature will be popular among them.