C# 6.0 is around for a while but in the last couple weeks, I spoke with many programmers who don’t know anything about the new features. Therefore I want to present some of the new features in this post.
To use C# 6.0 you need at least Visual Studio 2015 which has the new Roslyn compiler which is needed for C# 6.0. Theoretically, you could install the compiler for older versions but I would recommend using the new Visual Studio versions if possible.
Whats new in C# 6.0
I will only present a few features of C# 6.0 in this post. For all new features please see the official documentation.
the new read-only properties enable real read only-behavior. To achieve this, just remove the setter as shown below.
String interpolation is my favorite new feature of C# 6.0. This new feature replaces the string.format and makes it easier and faster to combine strings and variables. To use this place a $ in front of the quotation mark of the string. Now you can write a variable directly into the string. You only have to put the variable in curly braces.
Expression-bodied functions can help to reduce unnecessary lines of code. You can use this new feature only when the method has only a single statement. Below you can see an example on how to use expression-bodied functions.
I don’t use this function too often because I like the method block. This makes it easier to read the code for me.
Using static brings some syntactic sugar to C# 6.0. You can declare a namespace static as shown below.
After you did this, it’s not necessary to qualify the class when using a method. For example, it is not necessary to use Math.PI. When you only have to use PI, the code gets easier to read.
Every programmer who uses objects has encountered a null reference exception. To prevent this C# 6.0 introduces the null-conditional operator. To prevent the throwing of a null reference exception, place the Elvis operator (?) after the element which might be null. The example below shows that if the person is null, “unknown” will be returned.
Without the ?? “unknown” part, null would have been returned. If you don’t return a value in case of null, you have to make sure that the left side of the = is a nullable value.
Nameof enables the developer to get the name of the variable. I used this feature for logging. With nameof I logged the class in which something happened. In the example below, you can see how you can achieve that.
Code and further reading
You can find the code examples on GitHub. A more extensive post about whats new in C# 6.0 can be found in the official documentation.
Comments powered by Disqus.