Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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));
like image 215
MaYaN Avatar asked Nov 09 '17 16:11

MaYaN


People also ask

Can you Destructure in C#?

Destructors in C# are methods inside the class used to destroy instances of that class when they are no longer needed. The Destructor is called implicitly by the . NET Framework's Garbage collector and therefore programmer has no control as when to invoke the destructor.

What is System ValueTuple?

ValueTuple is a structure introduced in C# 7.0 which represents the value type Tuple. It is already included in . NET Framework 4.7 or higher version. It allows you to store a data set which contains multiple values that may or may not be related to each other.

Is tuple a value type C#?

Tuple types are value types; tuple elements are public fields. That makes tuples mutable value types. The tuples feature requires the System.


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.

like image 133
M.kazem Akhgary Avatar answered Oct 17 '22 15:10

M.kazem Akhgary