Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an anonymous method accept variable number of arguments?

I'd like to be able to make inline calls to anonymous methods with variable number of arguments (sometimes with no arguments, sometimes with 11).

Dictionary<string, Action> ActionDic = new Dictionary<string, Action>();
int i = 0;
ActionDic["something"] = () => { i += 1; };           // this line is ok
ActionDic["somethingArgs"] = (int n) => { n += 1; };  // but this is not
    // Delegate 'System.Action' does not take 1 arguments

So I can't make a delegate accept arguments like that. Is my syntax wrong, or is it just not possible? Or do I have to change the type of anonymous method I should use for my dictionary?

like image 708
user1306322 Avatar asked Feb 01 '26 19:02

user1306322


1 Answers

You could use Action<int> if you want to define a delegate with 1 integer argument. For example:

Action<int> somethingArgs = (int n) => { n += 1; };

You haven't shown what the ActionDic variable is but if it is an IDictionary<string, Action> you cannot make this work because Action do not accept an argument.

What you could do on the other hand is to use a dictionary of delegates:

IDictionary<string, Delegate> ActionDic = ...
ActionDic["something"] = (Action)(() => { i += 1; }); 
ActionDic["somethingArgs"] = (Action<int>)((int n) => { n += 1; });
like image 158
Darin Dimitrov Avatar answered Feb 03 '26 07:02

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!