tags:

views:

59

answers:

2

Lets say I have the following code:

delegate int MyDel (int n);   // my delegate

static int myMethod( MyDel lambda, int n) { 
    n *= n;
    n = lambda(n);
    return n;      // returns modified n
}

This way, having different lambda expression I can tune the output of the Method.

myMethod ( x => x + 1, 5);
myMethod ( x => x - 1, 5);

Now, if I don't want to do any aritmethic in lambda expression, I could use:

myMethod ( x => x, 5);  // and lambda will simply return x

My question is, is there a way to use the lambda expresion with 'params' optional properties? Maybe somehow embedding my delegate in array?

 static int myMethod (int n, params MyDel lambda) { 
+3  A: 

Does this work?

EDIT Sorry, was doing this with one eye, let me rephrase that.

static int myMethod (int n, params  MyDel[] lambdas) {
Joachim VR
I think it should be `params MyDel[] lambdas`
Matt Ellen
+1  A: 

Yes you can.

    delegate int MyDelegate(int n);
    static void MyMethod(int n, params MyDelegate[] handlers)
    {
        for (int i = 0; i < handlers.Length; i++)
        {
            if (handlers[i] == null)
                throw new ArgumentNullException("handlers");
            Console.WriteLine(handlers[i](n));
        }
    }

    static void Main(string[] args)
    {
        MyMethod(1, x => x, x => x + 1);
        Console.Read();
    }

Output:

1

2

Danny Chen