styfle styfle - 4 months ago 20
C# Question

Destructuring assignment - object properties to variables in C#

JavaScript has a nifty feature where you can assign several variables from properties in an object using one concise line. It's called destructuring assignment syntax which was added in ES6.

// New object
var o = {p1:'foo', p2:'bar', p3: 'baz'};
// Destructure
var {p1, p2, p3} = o;
// Use the variables...
console.log(p1.toUpperCase()); // FOO

I want to do something similar with C#.

// New anonymous object
var o = new {p1="foo", p2="bar", p3="baz"};
// Destructure (failing)
var {p1, p2, p3} = o;
// Use the variables...
Console.WriteLine(p1.ToUpper()); // FOO

Is there a syntax to do this in C#?


Closest thing which could help you are Tuples.

C#7 maybe will have something like this:

public (int sum, int count) Tally(IEnumerable<int> values) 
    var res = (sum: 0, count: 0); // infer tuple type from names and values
    foreach (var value in values) { res.sum += value; res.count++; }
    return res;

(var sum, var count) = Tally(myValues); // deconstruct result
Console.WriteLine($"Sum: {sum}, count: {count}"); 

Link to discussion

Right now it is not possible.