Is there any implementation in C# like JavaScript\'s spread syntax?
var arr = new []{
\"1\",
\"2\"//...
};
Console.WriteLine(...arr);
One trick to get a behavior similar to this (without reflection) is to accept params SomeObject[][]
and to also define an implicit operator from SomeObject
to SomeObject[]
. Now you can pass a mixture of arrays of SomeObject
and individual SomeObject
elements.
public class Item
{
public string Text { get; }
public Item (string text)
{
this.Text = text;
}
public static implicit operator Item[] (Item one) => new[] { one };
}
public class Print
{
// Accept a params of arrays of items (but also single items because of implicit cast)
public static void WriteLine(params Item[][] items)
{
Console.WriteLine(string.Join(", ", items.SelectMany(x => x)));
}
}
public class Test
{
public void Main()
{
var array = new[] { new Item("a1"), new Item("a2"), new Item("a3") };
Print.WriteLine(new Item("one"), /* ... */ array, new Item("two"));
}
}