Iva
Iva

Reputation: 367

Execute function with name stored as a value in a dictionary

I have created a dictionary, where funcDef is a name of a function. For example, some of the elements I add to my dictionary:

dict.Add("Banana", (a, b) => getNumberofBananas(a, b));
dict.Add("Apple", (a, b) => getNumberofApples(a, b));

Where getNumberofApples/Bananas are public functions implemented in the same class. I can get the function I need when I type

dict.Remove(string myKey)

But how can I call it to execute?

Upvotes: 2

Views: 323

Answers (4)

David L
David L

Reputation: 33853

Simply retrieve the value by string key and invoke it, passing the appropriate arguments.

int numberOfBananas = dict["Banana"](a, b);

Remove will remove the entry from your dictionary, which is probably not what you're trying to accomplish.

It's worth noting that based on how you are currently adding your functions to your dictionary, your parameters are captured upon registration and the runtime parameters will be ignored. If you want to provide values at runtime, consider using the following syntax instead.

dict.Add("Banana", getNumberofBananas);

Upvotes: 3

Jashaszun
Jashaszun

Reputation: 9270

If you really want to call your function and then remove it:

dict["Banana"](a, b);
dict.Remove("Banana");

Where a and b are the arguments to the function you're calling.

I'm not sure how in your code dict.Remove("...") returns a function, because documentation says that it returns a bool saying whether or not the element was removed.

Upvotes: 1

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149588

You don't want to remove the element from your dictionary. You'll need to extract it from the dictionary and invoke it. Assuming your delegates are of type Func<int, int, int>:

If you're sure the key is present, then do:

var result = dict["Apple"](a, b);

Or (to show you what actually happens):

var func = dict["Apple"];
var result = func(a, b);

Otherwise, use Dictionary.TryGetValue:

Func<int, int, int> func;
if (!dict.TryGetValue("Apple", out func))
{
    // No such function
}

int result = func(a, b);

Upvotes: 1

Luaan
Luaan

Reputation: 63772

Just like anything else:

dict["Banana"](a, b);

Remove... well... removes the element. All you need is to read it - that's what indexers are for. Invoking the delegate is then just about adding the parentheses and arguments.

Upvotes: 1

Related Questions