4

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) { 

2 Answers 2

3

Does this work?

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

static int myMethod (int n, params  MyDel[] lambdas) {
Sign up to request clarification or add additional context in comments.

1 Comment

I think it should be params MyDel[] lambdas
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.