Maxime Joyal Maxime Joyal - 8 months ago 33
C# Question

How to associate a value to a function call?

Many times I had to do stuff similar to this:

if (value == certainValueA) call functionA()
if (value == certainValueB) call functionB()

I've always done it like this. However now I have over 50 cases like this, and this way seems bad.

I'd like a more efficient way to do it. The solution is probably well documented, but so far the combination of words I'm using to find such a things doesn't return any interesting results.

I mostly need a direction on what to look into.


You can use a Dictionary filled with delegates; something like:

var dispatch = new Dictionary<TypeOfValue, Action>() {
    { certainValueA, () => functionA() },
    { certainValueB, () => functionB() },

TypeOfValue value = // get value here