Using Tuples in Deconstructors
[C#, .NET]
In C#, you would typically write a constructor like this:
public sealed class Spy
{
public Spy(string firstName, string surname)
{
FirstName = firstName;
Surname = surname;
}
public string FirstName { get; }
public string Surname { get; }
}
Pretty straightforward.
You might be interested to know that you can use expression body constructors and ValueTuples to simplify this further:
public sealed class Spy
{
public Spy(string firstName, string surname) => (FirstName, Surname) = (firstName, surname);
public string FirstName { get; }
public string Surname { get; }
}
I’ve written about this technique before here.
For trivial functionality such as field assignments, tuples
can simplify your code.
You can also make use of this technique for deconstructors.
This is a technique you can use to allow properties of your class be returned individually, allowing you to write code like this:
var spy = new Spy("James", "Bond");
// Deconstruct our type
var (firstname, surname) = spy;
Console.WriteLine($"The first name is {firstname}");
Console.WriteLine($"The last name is {surname}");
You would write one like this:
public void Deconstruct(out string firstname, out string surname)
{
firstname = FirstName;
surname = Surname;
}
This can also be rewritten using tuples
as follows:
public void Deconstruct(out string firstname, out string surname) => (firstname, surname) = (FirstName, Surname);
TLDR
You can use tuples in constructors to assign fields, as well as to deconstruct types.
The code is in my GitHub.
Happy hacking!