C++/CLI switch on String
.net, c++-cli, string, switch-statement
Solution
Actually, you can use anything other than integers (sometimes designated by integral types) if the tested objects defines conversion to integer.
String object do not.
However, you could create a map with string keys (check that the comparison is well processed) and pointers to classes implementing some interface as values:
class MyInterface {
public:
virtual void doit() = 0;
}
class FirstBehavior : public MyInterface {
public:
virtual void doit() {
// do something
}
}
class SecondBehavior : public MyInterface {
public:
virtual void doit() {
// do something else
}
}
...
map<string,MyInterface*> stringSwitch;
stringSwitch["val1"] = new FirstBehavior();
stringSwitch["val2"] = new SecondBehavior();
...
// you will have to check that your string is a valid one first...
stringSwitch[val]->doit();
A bit long to implement, but well designed.
Problem
In other .NET languages such as C# you can switch on a string value: ``` string val = GetVal(); switch(val) { case "val1": DoSomething(); break; case "val2": default: DoSomethingElse(); break; } ``` This doesn't seem to be the case in C++/CLI ``` System::String ^val = GetVal(); switch(val) // Compile error { // Snip } ``` Is there a special keyword or another way to make this work for C++/CLI as it does in C#?