Reputation: 376
Is there a way to "unroll" parameters to a method/constructor from a List in C# or any language? Does this kind of feature have a name?
Basically I'm looking to simplify this piece of code:
var thick = new List<double>{ 1.0, 2.0, 3.0, 4.0 };
var t = new Thickness(thick[0], thick[1], thick[2], thick[3])
I'm specifically asking about the calling code, I'm aware that the framework could change the method declaration to take a params double[]
.
And if this is not possible, is it because of type safety concerns?
Upvotes: 0
Views: 346
Reputation: 111830
No. In C# there is no implicit/explicit parameter unrolling, like the javascript apply()
.
There is an explicit parameter "collection" that is the params
keyword. This must be defined in the method signature, but is probably more similar to the arguments
array in Javascript. Note that it is only compatible with an array, not a list. The signature must be params SomeType[] arg
. So to pass a List<>
you have to ToArray()
it (I consider it to be a waste of machine space and machine memory).
This feature isn't probably present because C# is strongly typed and a parameter collection would be needed to be checked at runtime (to see if the array length is correct, what types of parameters are used to select an overload and so on).
Using reflection you can use a parameter array. The Invoke()
method has as one argument an object[]
that must contain all the parameters.
Quite strangely even using the dynamic
keyword you can't use a parameter array. This probably because even with dynamic
the exact number of parameters must be known at compile time, but with a parameter array this wouldn't be known.
Upvotes: 7
Reputation: 17858
I apologise strongly as I have "man flu" atm so my IQ is sub shoesize.
but : you can convert the list to an array and send it to parameters.
List<String> s = new List<string>() { "HELLO", "THIS", "IS" };
thing(s.ToArray());
private static void thing(params object[] x)
{
foreach (object param in x) Console.WriteLine(param);
}
Upvotes: 1