Search code examples
c#c#-7.0valuetuple

How to create a List of ValueTuple?


Is it possible to create a list of ValueTuple in C# 7?

like this:

List<(int example, string descrpt)> Method()
{
    return Something;
}

Solution

  • You are looking for a syntax like this:

    List<(int, string)> list = new List<(int, string)>();
    list.Add((3, "first"));
    list.Add((6, "second"));
    

    You can use like that in your case:

    List<(int, string)> Method() => 
        new List<(int, string)>
        {
            (3, "first"),
            (6, "second")
        };
    

    You can also name the values before returning:

    List<(int Foo, string Bar)> Method() =>
        ...
    

    And you can receive the values while (re)naming them:

    List<(int MyInteger, string MyString)> result = Method();
    var firstTuple = result.First();
    int i = firstTuple.MyInteger;
    string s = firstTuple.MyString;