Deconstructing Non-Tuples

The ‘Tuple evolution‘ in C# 7x has created increased possibilities of C# like never before, both in terms of performance as well as readability. One of the nicest feature that came along has been the Deconstruction of tuples.

Deconstructing Tuples

The tuple data structure allows us to bundle together a finite number of values without having to go through the pain of creating a dedicated Data structure for it. This is often useful when we need to return more than one values from a method. Consider the following method.

private Tuple GetPerson()  =>  new Tuple("Jia", 2);

Prior to C# 7, this is where the fun ended. While it was easier to return multiple values from a method, it was a tedious task to read those data.

var person = GetPerson();

As you can see, this resulted in the code readability hitting rock bottom. But C# 7.0 has changed the picture completely and has made the Tuples not just more powerful, but extremely easy to use. Let’s rewrite the method as well as the caller access in C# 7.x.

private (string,int) GetPerson() => ("Jia",2);
var (name,age) = GetPerson();

As evident from the code, the readability and ease to use has increased, and that is not limited to just the caller. Even the way we return the method signature and return statement has become far more simpler.

Deconstructing Non-Tuples

The whole deconstruction process has made usage of tuple so flexible. What if we could leverage the same functionality in the non-tuples data structures ? Consider the following class.

class Person
  public string Name { get; set; }
  public int Age { get; set; }

  public Person(string name,int age)
    Name = name;
    Age = age;

private Person GetPerson() => new Person("Jia",2);
var person = GetPerson();

Of course it is easy to access the Name/Age Properties using the person.Name, person.Age syntax. But there could be situation when the Person class has many other properties and you are interested only in just a couple. Or there could be another situation when you want to assign the Name and Age properties directly to existing variables in the caller method. In such scenarios, we would have to write the following code.

// where 'name' and 'age' are variables in caller method.
var person = GetPerson();
name =  person.Name;
age  = person.Age;

C# 7.0 has made life things easier with the Deconstruct for non-tuples. All we need to do is add a simple Deconstruct method to the Person class.

public void Deconstruct(out string name, out int age)
  name = Name;
  age = Age;

The parameters of the Deconstruct method needs to be out parameters. That’s all you need to do for deconstruction of non-tuples to be effective. The code in question could be now rewritten as following.

(name,age) = GetPerson();

C# 7.x is turning out to be an interesting evolution of C# language. Eagerly waiting to see what is in store for C# 8.0.


One thought on “Deconstructing Non-Tuples

Comments are closed.