How can I Deconstruct Value Tuples that are out parameters in C# 7?

Viewed 2923

Given the following:

var dic = new Dictionary<string, (int, int)>()
{
    ["A"] = (1, 2)
};

dic.TryGetValue("A", out (int, int) value);

I can easily get the value out of the dictionary, but how can I deconstruct it to get each individual values so something like this:

dic.TryGetValue("A", out var (left, right));
1 Answers

dic.TryGetValue("A", out var (left, right));

This syntax is not yet supported, it may be added in future. reference


You can give tuple elements name like this.

if(dic.TryGetValue("A", out (int left, int right) t))
{
    var (left, right) = (t.left, t.right);

    // use (left, right) or directly use (t.left, t.right)
}

I couldn't think of shorter syntax, Its just matter of time. c#7 is evolving faster than before so you just have to wait.

Related