C# 6.0 - what's new

Published on 2017-11-22 by Raul

Here's a video containing the latest additions in C# 6.0.

In short:

1. getter-only auto-properties:

public int X { get; }

 

2. initializers for auto-properties: 

public int X { get; } = 5;

 

3. using for static classes: 

use System.Math; 

//then, in your code, you can call:
Sqrt(25);

 

4. String interpolation (String.Format getting better)

//instead of
var x = string.Format("({0}, {1})", a, b);

//you can do:
var x = "(\{a}, \{b})";

 5. Expression-bodied methods:

//instead of 
public string ToString() 
{
	return "my string";
}

//you can do
public string ToString() => "my string";

 6. Expression-bodied properties

//instead of
public string MyProperty
{
	get { return myValue; }
}

//you can do
public string MyProperty => myValue

 7. Index initializers

//before:
var obj = new JObject();
obj["x"] = x;
obj["y"] = y;

//after:
var obj = new JObject() { ["x"] = x, ["y"] = y };

 8. Null-conditional operators

//before
if(json != null 
	&& json["x"] != null
	&& json["x"].Type == JsonType.Integer
	&& json["y"] != null
	&& json["y"].Type == JsonType.Integer)
{
	//do something
}
//or
var onCh = OnChanged;
if(onCh != null)
	onCh(this, args);

//after
if(json?["x"]?.Type == JsonType.Integer
	&& json?["y"]?.Type == JsonType.Integer)
{
	//do something
}
//or
var onCh = OnChanged?.Invoke(this, args);

 9. nameof

//before
throw new ArgumentNullException("point"); 
//what if you change the name of the variable?

//after
throw new ArgumentNullException(nameof(point)); 

 10. Exception filters

//before
try
{
}
catch(MyException me)
{
	if(!me.IsSevere) throw;
}

//after
try
{
}
catch(MyException me) if (me.IsSevere)
{

}

 11. Await in catch and finally

 


Keep in touch


About

Hey there, I'm Raul, owner of CreativeCLR, a small consulting company.

Feel free to drop me any question you might have on this post using the comment section or the contact page.