Ruby Rain
Ruby Rain

Reputation: 165

How to use Func from Dictionary

What I'm trying to do, is to call a specific function for a specific Key. For example, if the is key is '+', I want to call Sum function. I already created a Dictionary, and added a Key and a function.

Func<int, int, int> Sum = (a, b) => a + b;
Dictionary<char, Func<int, int, int>> operations = new Dictionary<char, Func<int, int, int>>()
operations.Add('+', Sum);

I don't understand how to pass a values to my Sum Func, and how to store an answer somewhere.

Upvotes: 1

Views: 599

Answers (1)

Heinzi
Heinzi

Reputation: 172390

I don't understand how to pass a values to my Sum Func, and how to store an answer somewhere.

var operation = operations['+'];
var result = operation(1, 2); // yields 3

(fiddle)

If you want to emphasize that operation is a delegate rather than a "regular" method, you can write operation.Invoke(1, 2) instead of operation(1, 2).

Upvotes: 1

Related Questions