Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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} = o;
// Use the variables...
console.log(p1.toUpperCase()); // FOO
console.log(p2.toUpperCase()); // BAR

I want to do something similar with C#.

// New anonymous object
var o = new {p1="foo", p2="bar", p3="baz"};
// Destructure (wrong syntax as of C#6)
var {p1, p2} = o;
// Use the variables...
Console.WriteLine(p1.ToUpper()); // FOO
Console.WriteLine(p2.ToUpper()); // BAR

Is there a syntax to do this in C#?

like image 850
styfle Avatar asked Mar 02 '16 17:03

styfle


People also ask

How do you swap variables using Destructuring assignment?

[a, b] = [b, a] is the destructuring assignment that swaps the variables a and b . At the first step, on the right side of the destructuring, a temporary array [b, a] (which evaluates to [2, 1] ) is created. Then the destructuring of the temporary array occurs: [a, b] = [2, 1] .

What is Destructuring assignment?

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

What is Destructuring an object?

JavaScript Object Destructuring is the syntax for extracting values from an object property and assigning them to a variable. The destructuring is also possible for JavaScript Arrays. By default, the object key name becomes the variable that holds the respective value.


2 Answers

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.

like image 54
Szer Avatar answered Oct 07 '22 00:10

Szer


C# 7 Using Tuples. You can achieve something like this.

You can construct and destruct a Tuple. Snippet

var payLoad = (
    Username: "MHamzaRajput",
    Password: "password",
    Domain: "www.xyz.com",
    Age: "24" 
);

// Hint: You just need to follow the sequence. 

var (Username, Password, Domain, Age) = payLoad;
// or
var (username, password, _, _) = payLoad;

Console.WriteLine($"Username: {username} and Password: {password}"); 

Output

Username: MHamzaRajput and Password: password
like image 20
M. Hamza Rajput Avatar answered Oct 06 '22 23:10

M. Hamza Rajput