Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Switch with dictionary values?

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).

like image 262
user1306322 Avatar asked May 11 '12 18:05

user1306322


3 Answers

You want to use an enum, not a dictionary.

enum AnimalsEnum { Dog, Cat, Bird, Fish };


public whathuh(AnimalsEnum whichAnimal) {
 switch(whichAnimal) {
   case AnimalsEnum.Dog:
   case AnimalsEnum.Cat:
...
}

}
like image 79
Heather Avatar answered Sep 28 '22 12:09

Heather


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();
like image 36
scottm Avatar answered Sep 28 '22 10:09

scottm


It's not a VS restriction, it's a language restriction. So you won't be able to do exactly what you want. One idea would be to use an enum. An enum can't use a char value for it's entries, look at Why we can't have "char" enum types for some info on that.

like image 40
Sascha Avatar answered Sep 28 '22 10:09

Sascha