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?
+2
A:
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
2009-02-26 11:32:56
That's what I was afraid of! Perhaps I'll just use an if statement instead.
macleojw
2009-02-26 11:33:58
Correct, this isn't the case in VB.NET, it can be a variable there!
MrEdmundo
2009-02-26 11:34:37
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
2009-02-26 11:40:18
A:
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
2009-02-26 11:41:01
A:
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.
DrJokepu
2009-02-26 11:47:00