Can I use lambda expression with params keyword?

Suppose 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 } 

Thus, having a different lambda expression, I can customize the method output.

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

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

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

My question is: is there a way to use lambda expresion with additional params properties? Maybe somehow embed my delegate into an array?

  static int myMethod (int n, params MyDel lambda) { 
+4
source share
2 answers

It works?

EDIT Sorry, did it with one eye, let me rephrase it.

 static int myMethod (int n, params MyDel[] lambdas) { 
+3
source

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

+1
source

All Articles