Briefly exploring C# 6 new features






4.65/5 (78 votes)
briefly exploring most important new features of C# 6
A few weeks ago i was reading about some of the new features coming with C# 6 in different places. I've decided to gather them so you can check them out at once if haven't already. some of them may not as amazing as expected but that the update for now.
You can get them by downloading VS 2014 or installing the Roslyn package for visual studio 2013 from here.
Update:
i add new items to the Article once they are added to Roslyn download package or remove them once they are removed from Roslyn download package.
So lets get started:
1. $ sign
var col = new Dictionary<string, string>()
{
// using inside the intializer
$first = "Hassan"
};
//Assign value to member
//the old way:
col["first"] = "Hassan";
// the new way
col.$first = "Hassan";
2. Exception filters:
try
{
throw new Exception("Me");
}
catch (Exception ex) if (ex.Message == "You")
{
// this one will not execute.
}
catch (Exception ex) if (ex.Message == "Me")
{
// this one will execute
}
3. await in catch and finally block:
try
{
DoSomething();
}
catch (Exception)
{
await LogService.LogAsync(ex);
}
4. Declaration expressions
long id;
if (!long.TryParse(Request.QureyString["Id"], out id))
{ }
if (!long.TryParse(Request.QureyString["Id"], out long id))
{ }
5. using Static
using System.Console;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
//Use writeLine method of Console class
//Without specifying the class name
WriteLine("Hellow World");
}
}
}
6. Auto property initializer:
public class Person
{
// You can use this feature on both
//getter only and setter / getter only properties
public string FirstName { get; set; } = "Hassan";
public string LastName { get; } = "Hashemi";
}
7. Primary Constructor:
//this is the primary constructor:
class Person(string firstName, string lastName)
{
public string FirstName { get; set; } = firstName;
public string LastName { get; } = lastName;
}
8- Dictionary Initializer:
some people believed that the old way of initiailzing dictionaries was dirty so the C# team dicided to make it cleaner, thanks to them. here is an example of the old way and new way:
// the old way of initializing a dictionary Dictionary<string, string> oldWay = new Dictionary<string, string>() { { "Afghanistan", "Kabul" }, { "United States", "Washington" }, { "Some Country", "Some Capital city" } }; // new way of initializing a dictionary Dictionary<string, string> newWay = new Dictionary<string, string>() { // Look at this! ["Afghanistan"] = "Kabul", ["Iran"] = "Tehran", ["India"] = "Delhi" };