News from C# 6

hi everybody,

Have you heard some news about Roslyn. Theis project is a compiler entierely recasting.  The project is now an open source project and it’s available on codeplex.

Let’s take a look around about the new functions

 Using Static

Now you can make an using on an object. That permit to import all static method without type the object name. Here is an example with String.Concat :

using System.String;
…..
String a = « hello »;
String b = « world »;
Console.WriteLine(Concat(a, » « ,b, »! »);

 

Properties initialization

Now we can initialized properties to a default value at object initialization :

public class class1
{
public int cmpt {get;set;} = 42;
}

Note now you can create readonly property with the same syntax, but I prefer create a const member :

public class class1
{
public int cmpt {get;} = 42;
}

 

Improvement around primary constructor

This new syntax concern again the properties, you can set the property intial value when calling the method :

 

public class class1(int x, int y)
{
public int a {get;set;} =x;
public int b {get;set;} =y;
}

The syntax benefit is only at code line number, it’s better for understanding, but I think it will be useful.

dictionnary and indexed member initialization

Since  C# you can initialize dictionary  with a syntax not really intuitive :

var letters = new Dictionary<string, int>
{
{ « a », 1 },
{ « b », 2 },
{ « c », 3 },

};

Now there is two better way to initialize a dictionary :

var letters = new Dictionary<string, int>
{
[« a »] = 1,
[« b »] = 2,
[« c »] = 3,

};

 

Or

var letters = new Dictionary<string, int>
{
$a = 1,
$b = 2,
$c = 3,

};

The second one, I think, will be very useful for json object

Thus, you can access to indexed value with the manner :

 

int a = letters.$a

 

 Declaration scope for variable

Until now, a variable only could be declared in autonom statement, not in the midlle of a function. But sometime, we only need a temporar variable result of tryparse for example. Now it’s possible :

if (Decimal.TryParse(txtPrice.Txt, out decimal price))
product.Price = price;

 

Filtering exception

in VB.NET it’s already possible, and now in c# 6 we can do that like in VB :

try
{
using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{

}
}
catch(IOException ex) if (ex.HResult == 0x80070020)
{
// File is in use by another process
// Handle that case…
}
catch(IOException ex) if (ex.HResult == 0x80070035)
{
// Network path was not found
// Handle that case…
}
catch(Exception ex)
{
// Something else happened
// Handle that case…
}

This method target to clarify code, it will be very usefull

 

Conclusion

As we can see, lot of new function has arrived, and lot of more will come. The new statement are not vital but they simpligy developper life.  If you want to show all news implementation visit this page

Source : http://tlevesque.developpez.com/tutoriels/csharp/les-nouveautes-de-csharp-6/#L1-4