New stuff coming in C# 7.0

Mads Torgersen wrote a blog post highlighting what’s new in C# 7.0:

C# 7.0 adds a number of new features and brings a focus on data consumption, code simplification and performance.

The changes all seem to be in line with the recent trends of borrowing syntax sugar from other languages to C#. Nothing wrong with that: copy what’s good and shed what’s bad.

One of the changes is related to out variables. These are the C# way to deal with not being able to return multiple values (see below for good news on that front). It’s basically the same as passing by reference in, say, C. For instance:

int myOutVar;
changeMyOutVar(out myOutVar);

You could have the value of myOutVar set inside changeMyOutVar. Simple. What is changing in C# 7.0 is that you would no longer need to predeclare myOutVar:

changeMyOutVar(out int myOutVar);

The scope of the new variable will be the enclosing block. I have to say it: I don’t like it. It feels obfuscated to me. The variable doesn’t look like it should be in that scope. Compare with this popular Go idiom:

if err := DoSomething(); err != nil {
    return err;
}

The variable err is created inside the if and its scope is there as well. I know a lot of people who hate this for the same reason I don’t like the way the new out variables are to be created in C#. I find it much more clear in Go though.

The feature I absolutely loved to read about is tuples. Error handling in .NET is often done with exceptions, which I find clunky and cumbersome. With tuples, we might be able to move to something more Go-like:

(User, bool) FindUser(string username) {
    var found = _userList.Find(u => u.Username == username);
    if (found == null)
        return null, false;
    return found, true;
}

So we could do something like:

var (user, ok) = FindUser("someusername");
if (!ok) {
    // user not found, deal with this
}

Check his post for more features.

Roberto Selbach
Roberto Selbach
Software Engineer

Ever-learning gopher at HashiCorp.