In the latest C# 6.0 there are so many changes and improvements made. In this article I will list a few of the C# 6.0 features introduced. The features are:
- Auto-property initializers
- nameof expressions
- Null conditional operators
- Exception filters
- Await in catch and finally blocks
- Using Static
Auto-property Initializers
As a developer we encounter auto-properties every day. With the introduction of this new feature of auto-property initializer, the overhead of invoking a setter and initializing the property in the constructor is removed. This new feature of auto-property initializer will initialize the value to the property in the declaration only. For example:
- public class Employee
- {
- public string FirstName { get; set; } = "John";
- public string LastName { get; set; } = "Snow";
- }
This feature can also be used with read-only properties (properties with getters only) as in the following:
- public string FirstName { get; } = "John";
nameof Expressions
There are various scenarios we encounter in which we must provide some string literals that name some program element. For example, when throwing an ArgumentNullException, we want to name the invalid parameter, or when raising a PropertyChanged event we want to name the property that is changed, and so on. The string literals are error-prone and can be misspelled that cannot be validated at compile time. By using nameof expressions, the compiler checks the referred name.
- if (obj == null) throw new ArgumentNullException(nameof(obj));
Null-conditional operator
The null-conditional operator checks for a null value before invoking any member. This will let you invoke or access the members only if the variable is not null. For example:
- int? _count = employees?.Count();
The null conditional operator can be used with the null-coalescing operator (??) to assign some default value if the returned value is null. For example:
- int _count = employees?.Count() ?? 0;
Exceptions Filters
This feature was already present in VB and F# but newly introduced in C#. Using exception filters one can specify an if condition in the catch statement. In case the if condition evaluates to true only then the catch will be executed. For example:
- try
- {
-
- }
- catch(exception ex) if(ex.Message == “Test”)
- {
-
- }
Await in catch and finally blocks
With C# 6.0 a new feature is added to exception handling. Now we can use an await in catch and finally statements. For example:
- try
- {
-
- }
- catch(Exception ex)
- {
- await LogAsync(ex);
- }
Using Static
In C# 6.0, a different kind of using clause is introduced by which we can access static members directly. For example:
- using System.Console;
- namespace MyConsoleApp
- {
- class Sample
- {
- static void Main(string[] args)
- {
- WriteLine(“Hello!!!”);
- }
- }
- }