a blog for those who code

Friday, 6 March 2015

New Features in C# 6.0 - Part 1

In this post we will discuss about the new features in C# 6.0. The new features in C# 6.0 are String Interpolation, nameof Expressions, Exception Filters, Enhancement to Auto Properties, Null-conditional operators, Expression-bodied methods, Dictionary Initializer and Await in catch and finally blocks.

1. String Interpolation

In the previous versions of C# we used string.Format as

Console.WriteLine(String.Format("({0}, {1})", a, b));

In C# 6.0, we can put expressions directly in the string literal to show the values in a proper formatted manner. We can even write conditions within string literals with additional strings as content.

Console.WriteLine(String.Format("(\{a}, \{(b == 10 ? true : false)})"));

2. nameof Expressions

In C# 6.0 we have a new keyword named "nameof" which can be used to create the expression to specify the name. Foe example nameof(Class) will return string literal "Class" and nameof(class.ClassA) will return string literal "ClassA".

public void newFeatures(Class class)
{
if(class == null) throw new ArgumentNullException(nameof(class) + "is null");
}

instead of

public void newFeatures(Class class)
{
if(class == null) throw new ArgumentNullException("class is null");
}

3. Exception Filters

This is a CLR capability which is already present in Visual Basic and F#, but was not present in C#. It is added in C# 6.0. When we use Exception Filters catch block will will handle the exception of a specific type only when certain condition is true that is written in an exception filter clause.

try {
exception
}
catch (Exception ex) if(ex.HResult == 1)
{
// Execute only when ex.HResult equals to 1
}
catch (Exception ex) if(ex.HResult == 2)
{
// Execute only when ex.HResult equals to 2
}
catch (Exception ex) if(ex.HResult == 3)
{
// Execute only when ex.HResult equals to 3
}
catch (Exception ex) 
{
// Execute when exHResult is not equal to 1, 2 or 3.
}

4. Enhancement to Auto Properties

The new feature in C# 6.0 defines Auto-Property initializer to be initialized like fields. You need to place an equal sign "=" at the end of the property and write default value to it.

public string Name { get; set; } = "Name";
public int a {get;} = 1;

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment