tags:

views:

368

answers:

4

In python, I can do something like this:

List=[3, 4]

def Add(x, y):
    return x + y

Add(*List) #7

Is there any way to do this or something similar in C#? Basically I want to be able to pass a List of arguments to an arbitrary function, and have them applied as the function's parameters without manually unpacking the List and calling the function explicitly specifying the parameters.

A: 

With LINQ you can do this which is pretty close to your example.

 var list = new List<int> { 3, 4 };
 var sum = list.Sum();
Brian Rasmussen
That isn't quite the same thing as using them as method arguments... but it may be what the OP wants...
Marc Gravell
You're right, but I wasn't sure exactly what the OP was looking for.
Brian Rasmussen
+3  A: 

Well, the closest would be reflection, but that is on the slow side... but look at MethodInfo.Invoke...

Marc Gravell
+1  A: 

you cant, you can do things that are close with a bit of hand waving (either yield to a foreach, or add a foreach extension method on the collection that takes a lambda), but nothing as elegant as you get in python.

Matt Briggs
A: 
Func<List<float>, float> add = l => l[0] + l[1];
var list = new List<float> { 4f, 5f };
add(list); // 9

or:

Func<List<float>, float> add = l => l.Sum();
var list = new List<float> { 4f, 5f };
add(list); // 9

Is the closest you get in c# considering it's statically typed. You can look into F#'s pattern matching for exactly what you're looking for.

Henrik