C# 7 – new features
C# is a powerful object-oriented language that is very easy to pick-up. The syntax is so simple but there are so many powerful and great features in C#. Some of the amazing features are lambdas, LINQ, generics, interfaces, async/await. They are all powerful concepts and it is a delight to use them with C#. With .NET Core being open source and cross-platform and ability to build for so many platforms and devices it is good to know ins and outs of the language.
With Visual Studio 2017 (March 7 – 2017) we got a new version of C# – C# 7.0. There is a lot of new exciting features that nicely build on top of existing ones.
Here is an overview of new features in C#:
- Out variables
- Pattern matching
- Local Functions
- Binary Literals
- Digit Separators
- Ref returns and locals
- Generalized async return types
- More expression-bodied members
- Throw expressions
Let us take a look at some of the new features that come with C# 7.
We usually use out variables when we use one of the TryParse method variants. Before, when we wanted to use TryParse we first had to define those variables.
That is not the case anymore, we can now directly declare it where we are passing it as a parameter:
It is quite common to return more than one value from a method and sometimes you don’t need or don’t want to use classes and objects because that’s just too much for the given purpose. Using out parameters can get quite ugly and they do not work with async methods. And you probably don’t want to use dynamic or ExpandoObject.
Tuples in C# 7 can now have multiple parameters, not only two like before. We use parentheses and inside of them types to denote the return type which tuple represents.
We can also have named tuple parameters:
When we use named parameters as we did in method GetSomeTuple then we get IntelliSense for these names as well and we can use them in our code.
We deconstruct tuples as you saw before. By using type and name of return parameter inside of parentheses:
However, we can also use var outside of the parentheses:
These two will be int ofc and compiler will pick up the type for you to know. You can’t use int explicitly in front of parentheses, you have to use var.
You could also have existing variables and deconstruct values into them:
Deconstruction without Tuples
We can also use deconstruction for any other type, as long as it has a deconstructor method in the following form:
That means we can have a custom type and a Deconstruct method on it and we can then deconstruct object/instance of that type:
This is just an example of syntax:
We could, of course, move the local functions at top of the SomeProduct method:
I like local functions better at the end of the methods than at the beginning. The code seems cleaner and it doesn’t prevent me from the easily reading the main part of the method.