Saturday, April 23, 2022

Destructuring assignment

ECMAScript, TypeScript, JavaScript

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

let a, b, rest;
[a, b] = [10, 20];

console.log(a);
// expected output: 10

console.log(b);
// expected output: 20

[a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(rest);
// expected output: Array [30,40,50]

C#

C# features built-in support for deconstructing tuples, which lets you unpackage all the items in a tuple in a single operation. The general syntax for deconstructing a tuple is similar to the syntax for defining one: you enclose the variables to which each element is to be assigned in parentheses in the left side of an assignment statement. For example, the following statement assigns the elements of a four-tuple to four separate variables:

var (name, address, city, zip) = contact.GetAddressInfo();

C# 'params'

By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array.

When you call a method with a params parameter, you can pass in:

    A comma-separated list of arguments of the type of the array elements.
    An array of arguments of the specified type.
    No arguments. If you send no arguments, the length of the params list is zero.

The following example demonstrates various ways in which arguments can be sent to a params parameter.

public static void UseParams(params int[] list)...


static void Main(){
    // You can send a comma-separated list of arguments of the
    // specified type.
    UseParams(1, 2, 3, 4);

    // An array argument can be passed, as long as the array
    // type matches the parameter type of the method being called.
    int[] myIntArray = { 5, 6, 7, 8, 9 };
    UseParams(myIntArray);

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

source: https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/deconstruct?wt.mc_id=academic-0000-chnoring

source: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

 

No comments:

Post a Comment