I have a function of this sort
void func(params object[] parameters) {
//Function Body
}
It can accept parameters of the following sort
func(10, "hello", 30.0);
func(10,20);
and so on.
I wanted to create an Action
delegate for the above function. Is it possible? If not then why?
This is where you run up against the limitations of functional programming in C#: you can not have a delegate with a variable number of generically-typed parameters (the
Action
delegates have a fixed number of generic parameters). But you may find it useful to create generic overloads for each number of parameters:What this gains you is the ability to pass those functions as parameters (ie, to pass them simply without using lambda expressions). So if you have a function like this:
Then you can call it like this:
You can't use the existing
Action
delegates withparams
, but you can declare your own delegate that way:Then:
Of course you can create an
Action<object[]>
for your existing method - but you lose theparams
aspect of it, as that's not declared inAction<T>
. So for example:So if you're calling the delegate from code which wants to use
params
, you need a delegate type which includes that in the declaration (as per the first part). If you just want to create a delegate which accepts anobject[]
, then you can create an instance ofAction<object[]>
using a method which hasparams
in its signature - it's just a modifier, effectively.