Is there any implementation in C# like JavaScript's spread syntax?
var arr = new []{ "1", "2"//... }; Console.WriteLine(...arr);
Spread syntax ( ... ) allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.
The JavaScript spread operator ( ... ) allows us to quickly copy all or part of an existing array or object into another array or object.
Summary. The spread operator allows us to spread the value of an array (or any iterable) across zero or more arguments in a function or elements in an array (or any iterable). The rest parameter allows us to pass an indefinite number of parameters to a function and access them in an array.
There isn't a spread option.
There isn't a spread option. And there are reasons.
However, having said that, you can get similar functionality with various language features.
Answering your example:
C#
var arr = new []{ "1", "2"//... }; Console.WriteLine(string.Join(", ", arr));
The link you provide has this example:
Javascript Spread
function sum(x, y, z) { return x + y + z; } const numbers = [1, 2, 3]; console.log(sum(...numbers)); // expected output: 6 console.log(sum.apply(null, numbers));
Params In C#, with same type
public int Sum(params int[] values) { return values.Sum(); // Using linq here shows part of why this doesn't make sense. } var numbers = new int[] {1,2,3}; Console.WriteLine(Sum(numbers));
In C#, with different numeric types, using double
public int Sum(params double[] values) { return values.Sum(); // Using linq here shows part of why this doesn't make sense. } var numbers = new double[] {1.5, 2.0, 3.0}; // Double usually doesn't have precision issues with small whole numbers Console.WriteLine(Sum(numbers));
Reflection In C#, with different numeric types, using object and reflection, this is probably the closest to what you are asking for.
using System; using System.Reflection; namespace ReflectionExample { class Program { static void Main(string[] args) { var paramSet = new object[] { 1, 2.0, 3L }; var mi = typeof(Program).GetMethod("Sum", BindingFlags.Public | BindingFlags.Static); Console.WriteLine(mi.Invoke(null, paramSet)); } public static int Sum(int x, double y, long z) { return x + (int)y + (int)z; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With