As you seem to be aware, lowercasing two strings and comparing them is not the same as doing an ignore-case comparison. There are lots of language-specific reasons for this.
Unfortunately, switch
doesn't do anything but an ordinal comparison.
What I have done in the past to get the correct behavior is just mock up my own switch statement. There are lots of ways to do this. One way would be to create a List<T>
of pairs of case strings and delegates and just loop through the list doing to proper comparison, and then invoke the delegate that matches.
The great thing about this is that there isn't really any performance penalty in mocking up your own switch functionality when comparing against strings. The system isn't going to make a O(1) jump table the way it can with integers, so it's going to be comparing each string one at a time anyway.
Something like this:
delegate void CustomSwitchDestination();
List<KeyValuePair<string, CustomSwitchDestination>> customSwitchList;
CustomSwitchDestination defaultSwitchDestination = new CustomSwitchDestination(NoMatchFound);
void CustomSwitch(string value)
{
foreach (var switchOption in customSwitchList)
if (switchOption.Key.Equals(value, StringComparison.InvariantCultureIgnoreCase))
{
switchOption.Value.Invoke();
return;
}
defaultSwitchDestination.Invoke();
}
Of course, you will probably want to add some standard parameters a return type to the CustomSwitchDestination delegate, and you'll want to make better names!
If your behavior of each of your cases is not amenable to delegate invocation in this manner, such as if differnt parameters are necessary, then your stuck with chained if statments. I've also done this a couple of times.
if (s.Equals("house", StringComparison.InvariantCultureIgnoreCase))
{
s = "window";
}
else if (s.Equals("business", StringComparison.InvariantCultureIgnoreCase))
{
s = "really big window";
}
else if (s.Equals("school", StringComparison.InvariantCultureIgnoreCase))
{
s = "broken window";
}