How to create a List of ValueTuple?

ArthNRick picture ArthNRick · May 29, 2017 · Viewed 34.5k times · Source

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

like this:

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

Answer

Guilherme picture Guilherme · May 29, 2017

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;