How to use Switch with dictionary values?
c#, dictionary, switch-statement
Solution
You could store a `Func<T>` or `Action` in the dictionary instead.
var dict = new Dictionary<int, Action>();
dict.Add(1, () => doCatThing());
dict.Add(0, () => doDogThing());
dict.Add(2, () => doFrogThing());
Then, use it like so:
var action = dict[1];
action();
Problem
In my code, I'd like to work with textual names of the items that are coded as one symbol in packets. In a usual situation, `1012` would mean `cat, dog, cat, frog` to me, but there are many more pairs like this, so it's hard to remember all of them. Sometimes they need to be changed, so I thought I should use a `Dictionary<string, int>` for that purpose. But then… ``` switch (symbol) { case "0": { /* ... */ } case "1": { /* ... */ } case "2": { /* ... */ } case "n": { /* ... */ } } ``` …becomes… ``` switch (symbol) { case kvpDic["cat"]: { /* ... */ } case kvpDic["dog"]: { /* ... */ } case kvpDic["frog"]: { /* ... */ } case kvpDic["something else"]: { /* ... */ } } ``` and the studio says I need to use constants for my switch. How do I make it work? Upd: number of such animals and their value pairs are only known at runtime, so the code must not use constants (I guess).