What’s New in C# 7.0

What’s New in C# 7.0

1

C# 7.0 adds a number of new features and brings a focus on data consumption, code simplification and performance. Perhaps the biggest features are tuples, which make it easy to have multiple results, and pattern matching which simplifies code that is conditional on the shape of data. But there are many other features big and small. We hope that they all combine to make your code more efficient and clear, and you more happy and productive.

Please use the “send feedback” button at the top of the Visual Studio window to tell us if something is not working as you expect, or if you have thoughts on improvement of the features.There are still a number of things not fully working in Preview 4. In the following I have described the features as they are intended to work when we release the final version, and called out in notes whenever things don’t yet work as planned.

I should also call out that plans change – not least as the result of the feedback we get from you! Some of these features may change or disappear by the time the final release comes out.If you are curious about the design process that led to this feature set, you can find a lot of design

Out variables

Currently in C#, using out parameters isn’t as fluid as we’d like. Before you can call a method with out parameters you first have to declare variables to pass to it. Since you typically aren’t initializing these variables (they are going to be overwritten by the method after all), you also cannot use var to declare them, but need to specify the full type .

public void PrintCoordinates(Point p)
{
int x, y; // have to “predeclare”
p.GetCoordinates(out x, out y);
WriteLine($”({x}, {y})”);
}

In C# 7.0 we are adding out variables; the ability to declare a variable right at the point where it is passed as an out argument:

public void PrintCoordinates(Point p)
{
p.GetCoordinates(out int x, out int y);
WriteLine($”({x}, {y})”);
}

A common use of out parameters is the Try… pattern, where a boolean return value indicates success, and out parameters carry the results obtained:

public void PrintStars(string s)
{
if (int.TryParse(s, out var i)) { WriteLine(new string(‘*’, i)); }
else { WriteLine(“Cloudy – no stars tonight!”); }
}

About the author

admin administrator

Leave a Reply