C# 12 has added the spread feature.
int[] row0 = [1, 2, 3];
int[] row1 = [4, 5, 6];
int[] row2 = [7, 8, 9];
int[] single = [..row0, ..row1, ..row2];
foreach (var element in single)
{
Console.Write($"{element}, ");
}
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12
Old answer (pre C# 12)
There isn't a spread option, but some useful alternatives.
- Method Parameters aren't an array in C# unless you use the params keyword
- Method Parameters that use the param keyword would have to either:
- Share the same type
- Have a castable shared type such as double for numerics
- Be of type object[] (as object is the root type of everything)
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;
}
}
}
paramsis as close as you're going to get.paramsin parameter will be more much likely an answer. Thanks @Robctx.users.Select(u => new { u.id, u.otherfields } ).ToList().ConvertAll(u => new { ...u, someList.FirstOrDefault(l => l.userid == u.id).something})...syntax is not an operator. In the specification, it is referred to in the language grammar asSpreadElement, though informally called the "spread syntax" since it is not a context-free grammar.(a, b, ...others) = getTwoParamsAndOthersIntoArray()- not sure why this syntax wouldn't make less sense in C# than JS now it has dynamics, value tuples and deconstruction :)