Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

C# 7: New Features

It seems like only yesterday we got C# 6, but as it goes in software development land, the next thing is already on its way. In this post I want to describe the most likely new C# 7 features, what they look like and why they’re useful.

C# 7 Tuples

What?

Tuples are a temporary grouping of values. You could compare a Tuple to a POCO-class, but instead of defining it as a class you can define it on the fly. The following is an example of such a class:

class PropertyBag
{
    public int Id {get; set;}
    public string Name {get; set;}
}
var myObj = new PropertyBag { Id = 1, Name = "test};

In the above example it wasn’t really necessary to name the concept we’re working with as it is probably a temporary structure that doesn’t need naming. Tuples are a way of temporarily creating such structures on the fly without the need to create classes

Why?

The most common reason for having a group of values temporarily grouped are multiple return values from a method. Currently, there are a few ways of doing that in C#:

Out parameters

public void GetLatLng(string address, out double lat, out double lng) { ... }

double lat, lng;
GetLatLng(myValues, out lat, out lng);
Console.WriteLine($"Lat: {lat}, Long: {lng}"); 

Using out-parameters has several disadvantages:

  • It cannot be used for async-methods
  • You have to declare the parameters upfront (and you can’t use var, you have to include the type)

Tuple-type

There currently already is a Tuple-type in C# that behaves like a native tuple. You could rewrite the previous method as follows:

public Tuple GetLatLng(string address) { ... }

var latLng = GetLatLng("some address");
Console.WriteLine($"Lat: {latLng.Item1}, Long: {latLng.Item2}"); 

This does not have the disadvantages of out-parameters, but the resulting code is rather obscure with the resulting tuple having property names like Item1 and Item2.

Class / struct

You could also declare a new type and use that as the return type:

struct LatLng{ public double Lat; public double Lng;}
public LatLng GetLatLng(string address) { ... }

var ll= GetLatLng("some address");
Console.WriteLine($"Lat: {ll.Lat}, Long: {ll.Lng}"); 

This has none of the disadvantages of out-parameters and the tuple type, but it’s rather verbose and it is meaningless overhead.

How?

There are a few different use cases for tuples that will be available with C# 7 Tuples:

Tuple return types

You can specify multiple return types for a function, in much the same syntax as you do for specifying multiple input types (method arguments)

public (double lat, double lng) GetLatLng(string address) { ... }

var ll = GetLatLng("some address"); 
Console.WriteLine($"Lat: {ll.lat}, Long: {ll.lng}");  

Inline tuples

You could also create tuples inline:

var ll = new (double lat, double lng) { lat = 0, lng = 0 };

Tuple deconstruction

Because the bundling of the values is not important as a concept, it’s quite possible that you don’t want to access the bundle at all, but get straight to the internal values. Instead of accessing the tuple properties as in the example of Tuple Return Types, you can also destructure the tuple immediately:

(var lat, var lng) = GetLatLng("some address");
Console.WriteLine($"Lat: {lat}, Long: {lng}");

C# 7 Record types

What?

A record type is a simple bag of properties, a data type with only properties

Why?

Often classes or structs are merely a collection of properties. They still need a full declaration which is quite verbose. The following class demonstrates that a class with 3 properties requires quite a bit of text to declare:

class MyPoint
{
    int _x;
    int _y;
    int _z;
    MyPoint(int x, int y, int z){
        this._x = x;
        this._y = y;
        this._z = z;
    }
    public int X {get{ return this._x;}}
    public int Y {get{ return this._y;}}
    public int Z {get{ return this._z;}}
}

How?

With record types you could write the above in a single line:

class Point(int X, int Y, int Z);

You will get a few more things out of this:

  • The class will automatically implement IEquatable, which means you can compare two record types based on their values instead of reference.
  • The ToString-method will output the values in the record

C# 7 Pattern Matching

What?

With record types in play, we can now get Pattern Matching built-in. Pattern matching means that you can switch on the type of data you have to execute one or the other statement.

Why?

Although pattern matching looks a lot like if/else, it has certain advantages:

  • You can do pattern matching on any data type, even your own, whereas if/else you always need primitives to match
  • Pattern matching can extract values from your expression

How?

The following is an example of pattern matching:

class Geometry();
class Triangle(int Width, int Height, int Base) : Geometry;
class Rectangle(int Width, int Height) : Geometry;
class Square(int width) : Geometry;

Geometry g = new Square(5);
switch (g)
{
    case Triangle(int Width, int Height, int Base):
        WriteLine($"{Width} {Height} {Base}");
        break;
    case Rectangle(int Width, int Height):
        WriteLine($"{Width} {Height}");
        break;
    case Square(int Width):
        WriteLine($"{Width}");
        break;
    default:
        WriteLine("");
        break;
}

In the sample above you can see how we match on the data type and immediately destructure it into its components.

Conclusion

The above are just three of a long list of new c# features coming soon. To me, they are the three most exciting features and I think they’ll be the ones which have the most impact on how we will write code in the future (together with non-nullable reference types and immutable types).

For more information about these and other new proposed features, head over to GitHub for the full list:

Work List of Features

NOTE: It’s still early days, the syntax of all of these can (and probably will) change. Some features might not even make it into C# 7 and have to wait until C# 8 or later. I encourage everyone to take a look on the GitHub page to examine and learn about these features. The discussion is quite lively there. If you have another good proposal, check out the same forums and maybe your feature gets the cut. It’s really nice that Microsoft has opened up all these channels, so we better make use of them!

For more information on the features described above, you can have a look at the full proposals here:

Proposal: Language support for Tuples
Proposal: Pattern matching and record types

The post C# 7: New Features appeared first on Kenneth Truyers.



This post first appeared on Kenneth Truyers Development, please read the originial post: here

Share the post

C# 7: New Features

×

Subscribe to Kenneth Truyers Development

Get updates delivered right to your inbox!

Thank you for your subscription

×