I've got a case statement in c#. I would like to chose the values for the cases from a configuration file at run time. Is this possible?
Asked
Active
Viewed 541 times
3 Answers
2
Not with a switch statement, no. The case labels have to be compile-time constants.
Marc Gravell has a switch-like construct you could use, somewhere... I'll try to find it. It may well not be suitable for your particular usage though.
Otherwise, a sequence of if/else if/else if [...] /else is the way to go.

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
That's what I was afraid of! Perhaps I'll just use an if statement instead. – macleojw Feb 26 '09 at 11:33
-
Correct, this isn't the case in VB.NET, it can be a variable there! – MrEdmundo Feb 26 '09 at 11:34
-
This one? Note I only included the idea - not the code... Personally, I'd just us `if` etc here ;-p http://stackoverflow.com/questions/156467/switch-pattern-matching-idea – Marc Gravell Feb 26 '09 at 11:40
0
As the values being used in a case statement in C# are expected to be constants I don't think it is possible to set these at runtime from a config file.

Andy Rose
- 16,770
- 7
- 43
- 49
0
As others have said, the switch statement needs the values at compile time since the underlying hash table is built at compile time. If you have entries that are determined at runtime, I would use hash tables / dictionaries with command pattern or delegates if I were you.

Tamas Czinege
- 118,853
- 40
- 150
- 176