My Most Favorite C# 7 Features

With Visual Studio 2017 out and C# 7 in the wild we got a couple of new features. After using them for a while, here are my favorites.

Out Variables
The change here is subtle and many would call it inconsequential but I love. Out variables can finally be declared inline instead of pre-declaring them above parsing statement. This small change makes code flow much smoother and, in my opinion, makes all the difference.
For example, note the difference between these two code fragments:

int count;
if (int.TryParse(text, out count) && (count > 1)) {
//do something with count
}
if (int.TryParse(text, out var count) && (count > 1)) {
//do something with count
}

For rare cases when you don't care about result you can also use underscore (_) character:

if (int.TryParse(text, out var _)) {
//do something
}

Throw Expressions
If you are creating classes for public consumption, quite often a big part of your code is boilerplate argument verification and throwing of exceptions. You can now merge usage of that argument with null coalescing or ternary operators. Again, nothing huge but makes code a bit more to the point:

if (text == null) { throw new ArgumentNullException(nameof(text), "Text cannot be null."); }
this.Text = text;

if (number >= 2) { thrown new ArgumentOutOfRange(nameof(number), "Number must be 2 or more."); }
this.Number = number;
this.Text = text ?? throw new ArgumentNullException(nameof(text), "Value cannot be null.");
this.Number = (number >= 2) ? number : throw new ArgumentOutOfRange(nameof(number), "Number must be 2 or more.");

Is Expressions
Another change that seems small but it really improves code is just another style of as operator and it will probably cause its demise. It is a syntax candy allowing for inline variable declaration and a bit more readable code:

var comboBox = sender as ComboBox;
if (comboBox != null) {
//do something with comboBox
}
if (sender is ComboBox comboBox) {
/do something with comboBox
}

Local Functions
And lastly, there are local functions. Again, these are nothing you couldn't do before. I don't think they are going to be used often most of the time. However, when you parse stuff or deal with state machines, they do come in handy as they do capture local variables.

Wish list

The only thing I still desire in C# as compared to other languages are enum methods. It is not a big thing but it would remove a whole set of helper methods and similar plumbing.

Leave a Reply

Your email address will not be published. Required fields are marked *