11

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.

ryeguy
  • 65,519
  • 58
  • 198
  • 260

4 Answers4

6

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

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
6

You can use the params keyword when defining your method and then you can directly put your list (after calling ToArray) in your method call.

public static void UseParams(params object[] list)
{
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
}

...which you can later call with the following.

object[] myObjArray = { 2, 'b', "test", "again" };
UseParams(myObjArray);

For reference: http://msdn.microsoft.com/en-us/library/w5zay9db.aspx

eremzeit
  • 4,055
  • 3
  • 30
  • 32
1

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
  • 41,224
  • 16
  • 95
  • 126
0
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
  • 9,714
  • 5
  • 53
  • 87
  • Your first suggestion will only work for lists with 2 elements. To make your first suggestion more general without using Sum() you could use Func, float> add = l => l.Aggregate((float)0, (aggregation, current) => aggregation + current); But Sum() seems to be the way to go here :) – Steven Wexler Apr 23 '13 at 16:36