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).
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:
...
}
}
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With