I have read through the New Features in C# 7.0 blog post on Microsoft Developer Network (MSDN) and also tried them using Visual Studio 2017.
My conclusion is that there is nothing revolutionary in C# 7.0. The features are all "nice to have" stuff.
My conclusion is that there is nothing revolutionary in C# 7.0. The features are all "nice to have" stuff.
Out variables
It is now possible to declare an out variable right where it is passed as an out argument. Example:
// Before C# 7.0
int x;
int y;
GetSomeInts(out x, out y);
// From C# 7.0
GetSomeInts(out int x, out int y);
Personally I think this can be good to limit the scope of variables when using the Try-pattern (a method that returns a boolean to indicate success or failure and results as out parameters):
if (TryParse(s, out string a, out string b))
{
// string a and b in scope and can be used here.
}
else
{
// string a and b not in scope.
}
Pattern matching
I am not a big fan of passing generic "objects" around and letting methods behave differently depending of the actual type of the object. To me this obfuscates the code. Maybe pattern matching can be used for other things as well, but in all examples I have seen so far it has been used to write methods that takes some kind of generic object as input, then tries to figure out the actual type, and then acts in different ways depending of the type.
In C# 7.0 you can even write Switch statements for generic types where the Case matches different derived types and acts differently depending of the type:
switch (shape) // Assume shape is of base class Shape that both Circle and Square is derived from
{
case Circle c:
area = Math.PI * c.Radius * c.Radius;
break;
case Square s:
area = s.Side * s.Side;
break;
default:
area = 0.0;
break;
}
My advice: Use with care, overuse of generic types makes it hard to understand what is going on in the code.
Tuples
Tuples has been improved in C# 7.0. And I like it. To me Tuples is a good way to group things that belong together without the need to write a separate class or struct.
When I first started working with C# I was a bit surprised that the support for Tuples was so limited. Making the support better is a good improvement. With C# 7.0 Tuples becomes really usable for the first time in C#.
Local functions
I need to play around with this a bit before I can give any recommendations. But it feels like a good way to encapsulate functionality that is not needed outside a specific method. The fact that local functions has access to parameters from the enclosing scope can be used to remove the need to give parameters to the function.
public void AMethod(double radius)
{
if (Area() < 10.0))
{
// Do something.
}
double Area()
{
return Math.PI*radius*radius;
}
}
There are some more new stuff available as well, read the MSDN blogpost for a list of all the goodies with code samples.
Kommentarer
Skicka en kommentar