After emergence of C# 6.0, adding features to the language gets really fast. Even some developers asked Microsoft to slow down! As a matter of fact, some features was implemented in C# 6.0 but the team decided to remove them from final release.
Here I want to describe 2 features in C# 7.0 with an interesting story.
out var declaration
This feature was really interesting as most of developers voted for it. To describe it, consider a method like bool void GetSumAndAvg(List<int> input, out sum, out avg) which calculates sum and average of the numbers in input array. As you need to return 2 values as a result of processing input , you need to use out in the signature. It can be used like:
string input = new List<int>() {34, 54, 64, 23, 12}; // You should declare the out variable to pass it to the method. int sum; int avg; GetSumAndAvg(input, out sum, out avg); Console.WriteLine(sum); Console.WriteLine(avg);
This proposal proposes this new way to facilitate calling methods with out parameters. Using this feature this code is valid:
string input = new List<int>() {34, 54, 64, 23, 12}; GetSumAndAvg(input, out var sum, out var avg); Console.WriteLine(sum); Console.WriteLine(avg);
In an other words, the variable declaration is happening within the method call.
Language support for Tuples
In this proposal you see how tuples is going to integrate into the language. So you can write GetSumAndAvg(input) with this signature:
Tuple<int sum, int avg> GetSumAndAvg(input)
and you can use it like:
var result = GetSumAndAvg(input); Console.WriteLine(result.sum); Console.WriteLine(result.avg);
As you see, this a very clean way to declare and use method with multiple outputs.
Lessons from these features
As you see, if the second feature exits in the language, there will be no need to first one. The second one is completely better that the first one. As I know, the "out var declaration" was ready to ship with C# 6.0, but they postponed it. I think it was smart, as features like "language support for tuples" and some other features like "Pattern Matching" are great replacements for it.
However, as lots of methods (like int.TryParse) are written previously and can not be ignored in the language, so there are still some reasons to add that feature to the language.
As a software architect, what decision would you take? Will you add it to the language and satisfy previous developers? Or do you prefer not to add it and make the language more straightforward?
I love "out variable declaration",it help me a lot 🙂
In my opinion we should wait and see what will be happen, although shorter code is clear and so pleased in comparison with long code, I prefer wait to being stable this method.