How to make C# Switch Statement use IgnoreCase

Tolsan picture Tolsan · Feb 25, 2010 · Viewed 78.9k times · Source

If I have a switch-case statement where the object in the switch is string, is it possible to do an ignoreCase compare?

I have for instance:

string s = "house";
switch (s)
{
  case "houSe": s = "window";
}

Will s get the value "window"? How do I override the switch-case statement so it will compare the strings using ignoreCase?

Answer

Nick Craver picture Nick Craver · Feb 25, 2010

A simpler approach is just lowercasing your string before it goes into the switch statement, and have the cases lower.

Actually, upper is a bit better from a pure extreme nanosecond performance standpoint, but less natural to look at.

E.g.:

string s = "house"; 
switch (s.ToLower()) { 
  case "house": 
    s = "window"; 
    break;
}