Search code examples
c#valuetuple

How does grouping data with parentheses work?


I recently came across this:

(int, string) tst = (0, "Test");

The idea behind it seems amazing, before whenever I wanted to map two variables I would use a KeyValuePair. It seems that this is available in .NET Core and not on the regular .NET 4.7.2 which is where I mostly program.

Am I missing something or this is only available on the .NET Core? What is the name of this variable grouping (so I can further research)? Is it the same as creating an object with two variables?

Here is an example:

(int, string) tst = (0, "Test");
var (k, b) = tst;

Console.WriteLine("k: " + k);
Console.WriteLine("b: " + b);

It's a silly question but thank you for the help.


Solution

  • You are looking at Tuples in the code in OP. Tuples were available before C# 7.0 too, but the improvements in Tuples (with introduction of ValueTuples) in C# 7.0 meant, one could use semantic names for fields of Tuples as seen in example.

    (int, string) tst = (0, "Test");
    

    In the above code, the tuples is unpacked and assigned to tst variable. This is known as deconstructing the tuple.

    Consider the following code from OP

    (int, string) tst = (0, "Test");
    var (k, b) = tst;
    

    You could combine this as

    var (k, b) =  (0, "Test");
    

    You could use Deconstruct in User Defined Types as well. For example, Consider the following code

    public class User
    {
        public string FirstName{get;set;}
        public string LastName{get;set;}
        public int Age{get;set;}
    }
    

    In order to support Deconstruct in above class, you could add a method as following.

    public class User
    {
        public string FirstName{get;set;}
        public string LastName{get;set;}
        public int Age{get;set;}
        
        public void Deconstruct(out string fName,out string lName,out int age)
        {
            fName = FirstName;
            lName = LastName;
            age = Age;
        }
    }
    

    The Deconstruct method has now enable us to support Deconstruction in the Class User. You could now write code similar to Tuple Deconstruct. For example,

    var user = new User{FirstName = "John", LastName="Doe",Age=50};
    var (fName,lName,age) = user;