Roslyn And C# 6 – With Visual 2015 being released, developers were treated to some really cool new language features in C# 6. In this article I will highlight some of the features available and compare some to the old way of doing things.
Roslyn And C# 6
Let’s jump right in to the juicy bits of C# 6. (Also note that all the code in the images are available on Pasetbin)
How long have we wanted to do this? Developers can now set initializers to auto-properties.
You can now exclude the setter and also initialize it.
Developers can now simplify methods with single return statements. This is done via the use of the Lambda Operator (#ProTip: Did you know that you can now debug Lambda Expressions in Visual Studio 2015?). Below you will see that the method DisplayErrorMessageOld() has been simplified into an Expression body called DisplayErrorMessageNew() by using the Lambda Operator.
Going Static On Using Statements
What this basically means is that you can now import static members into your class thereby removing the need to fully qualify the method. An example of this is the Math functions in C#. Back in the old days of C# (i.e. last month) developers had to fully qualify the math functions by using Math.Round for example.
In C# 6 we can now add the following using statement to our class: using static System.Math;
The math functions can now be used as is without qualification. Incidentally, you can also see the use of a nameof expression in the Exception. This allows you to provide a string that names a program element when throwing an exception. In the example above, when throwing an ArgumentException I want the name of the argument that caused the exception.
I have never liked using String.Format. It has always felt clunky and almost error-prone to me. Well in C# 6 developers are introduced to String Interpolation. Before this was available, developers would write out a string as something similar to this:
String Interpolation simplifies this code significantly. Consider the following line of code:
Doesn’t this remind you a bit of PHP? Nevertheless, this will make writing out strings much easier.
VB and F# have been at the party for ages…. in fact, they’re already on their second round of tequila. C# has only come to the party now with Exception Filters. Well it’s better late than never. If the expression between the parenthesis evaluates to true, the catch block is run.
I love using Lists in C#. In fact, I can comfortably say that I am a list junkie. Anyway, now I can indulge even more by giving my collections an initial set of elements. New syntax has been added to allow developers to set values to keys.
I am sure you will agree that C# 6 and Roslyn offer developers more than just the customary in-flight chicken or beef meal. Roslyn can be found on GitHub (yup, it’s open source). To see the code examples above in totality, check out the Pastebin code below.