Visual Studio 2015 recently introduced a new version of C# named C#6.0. I would not say it has major features added like Extension Method or LINQ in C# 3.0 or Async/ Await in C# 5.0. However it has many features that simplify the syntaxes and improve the readability of the code. Major C# 6.0 features include:
· Initializers for auto-properties
· Getter-only auto-properties
· Expression-bodied function members
· Using the static statement
· Null-conditional operators
· String interpolation
· nameof expressions
· Index initializers
· Exception filters
· Await in catch and finally blocks
· Extension Add methods in collection initializers etc.
In this post, I will discuss the top 5 five features of C# 6.0 (according to me J).
Auto-property initializers
In C# 6.0, a new feature has been added to set the default values of the public properties, called Auto-property initializers. Using the auto-property initializers, we can set default values to the properties without having to use a constructor. Let us consider a simple example of the Author class as shown in the listing below:
publicclassAuthor
{
publicstring Name { get; set; }
publicint Articles { get; set; } = 10;
}
As you notice in the above listing, the default value of the Articles property is set to 10. So while creating the object, if the value of the Articles property is not set then it would be set to the default value 10. In the below listing, we are not setting the value of the Articles property of the object a, hence it is set to the default value of 10.
Author a = newAuthor { Name = "DJ" };
Console.WriteLine(a.Name + " has authored " + a.Articles + " articles");
Console.ReadKey(true);
The auto-property initializer sets the value of the property directly into the backing field without invoking the setters. Prior to C# 6.0, we used to create read only properties by creating a private setter and then setting the value in the constructor. However in C#6.0, using the auto-property initializer, a read only property can be easily created as shown in the listing below:
publicclassAuthor
{
publicstring Name { get; set; }
publicint Articles { get; } = 10;
}
Creating a read only property with a default value is now super easy using the Auto-property initializer, making it one of my favorite feature of C# 6.0.
Support of using static statement for static members
Like me, do you also get tired of using the static class name each time while calling a method of the static class? For example, if you want to use the WriteLine of the static class Console, each time you need to use Console.WriteLine(“”). Again, this is not the biggest problem but still it annoys. C# 6.0 solves this problem by allowing us to make static members of a type available without the type prefix via new static directives. So we can simplify the use of the static class methods as shown in the listing below:
usingstatic System.Console;
namespace ConsoleApplication1
{
classProgram
{
staticvoid Main(string[] args)
{
Author a = newAuthor { Name = "DJ" };
WriteLine(a.Name + " has authored " + a.Articles + " articles");
ReadKey(true);
}
}
In the above snippet, we are including the System.Console class by using thestatic statement and then using methods like WriteLine, ReadKey etc. without having each time to add the class name of Console. This makes the code much cleaner.
String Interpolation
Remember string.format() ? We used that to perform string interpolation before C# 6.0. You may not have used it that much, but still it was complex to use, requiring you to match the exact variables name with the sequence to get expected output. Consider the listing below:
staticvoid Main(string[] args)
{
string name = "dj";
int age = 33;
string message = string.Format("{0} is {1} years old", name, age);
string wrongmessage = string.Format("{0} is {1} years old", age, name);
WriteLine(message);
WriteLine(wrongmessage);
ReadKey(true);
}
As you notice in the above listing in the variable wrongmessage, an unexpected value would get assigned because we have provided the wrong sequence of the variables. This is the problem with the string.format(). You will get output as shown below:
In C# 6.0, string interpolation is much simpler. Using the $ now, string interpolation can be done as shown in the listing below:
staticvoid Main(string[] args)
{
string name = "dj";
int age = 33;
string message = $"{name} is {age} years old";
WriteLine(message);
ReadKey(true);
}
As you see we are directly passing the variable name in the {}. This avoids the sequence problem of variables in string.format.
Exception Filter
One of my most favorite features of C# 6.0 is the Exception Filter. This allows an exception to be caught in the CATCH block, only a specified condition is met when the exception is thrown. Prior to C# 6.0, we did not have any mechanism to filter the exception in the catch block. We used the if-else statement in the same catch block to bring some sort of filter. To understand it better, let us consider the listing below:
staticvoid Main(string[] args)
{
int number = 24;
try
{
int rem = number % 0;
WriteLine(rem);
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
}
ReadKey(true);
}
The major problem in the above snippet is that we cannot apply a filter in the catch block. In C# 6.0, the exception filter can be applied as shown in the listing below:
staticvoid Main(string[] args)
{
int number = 24;
try
{
int rem = number % 0;
WriteLine(rem);
}
catch (DivideByZeroException ex) when (ex.Message.Contains("dj"))
{
WriteLine(ex.Message);
}
catch (DivideByZeroException ex) when (ex.Source == "ConsoleApplication1")
{
WriteLine(ex.Source);
}
ReadKey(true);
}
In C#6.0 using “when”, we can filter the exception. In the above snippet in particular, the catch statement will be thrown only when the condition in the when statement is true. The filtering exception could be very useful here.
Null Conditional Operators
Who hasn’t heard of NullReferenceException? I am sure all of us. To avoid this, we use enormous If conditions for null checking.
Let us consider the code listing below. We have a list of “Author”. Before fetching the Name of a particular Author, we are performing the null checking in if statement. If we do not do that, a NullReferenceException will be thrown.
staticvoid Main(string[] args)
{
Author author = null;
List<Author> lstAuthors = newList<Author>();
lstAuthors.Add(author);
foreach(var a in lstAuthors)
{
if (a != null)
{
var name = a.Name;
WriteLine(name);
}
}
ReadKey(true);
}
In C#6.0, we can avoid if statements by using Null Conditional Operators. We can rewrite the above code for the null checking as shown in the listing below:
staticvoid Main(string[] args)
{
Author author = null;
List<Author> lstAuthors = newList<Author>();
lstAuthors.Add(author);
foreach(var a in lstAuthors)
{
var name = a?.Name;
Write(name);
}
ReadKey(true);
}
In C#6.0 it is very easy to do the null reference checking using the null conditional operator (?). I am sure this feature would be wildly used, hence it’s one of my favorite features of C# 6.0.
So there we have it – my top five features of C#6.0. What are yours? In further posts, I explore others, but share your favorites in the comments. Thanks for reading!