94

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?

Pang
  • 8,605
  • 144
  • 77
  • 113
Tolsan
  • 1,104
  • 1
  • 7
  • 11

9 Answers9

79

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;
}
Nick Craver
  • 594,859
  • 130
  • 1,270
  • 1,139
  • @Nick, do you have any reference to the reason for the performance difference between the lower and upper conversions? Not challenging it just curious. – Lazarus Feb 25 '10 at 13:10
  • 1
    Yes, I understand that lowercasing is a way, but i want from it to be ignoreCase. Is there a way that i can override the switch-case statement? – Tolsan Feb 25 '10 at 13:10
  • 6
    @Lazarus - This is from CLR via C#, it was posted here a while back in the hidden features thread as well: http://stackoverflow.com/questions/9033/hidden-features-of-c/12137#12137 You can fire up LinqPad with a few million iterations, holds true. – Nick Craver Feb 25 '10 at 13:13
  • 1
    @Tolsan - No, unfortunately there's not just because of it's static nature. There was a good batch of answers on this a while back: http://stackoverflow.com/questions/44905/c-switch-statement-limitations-why – Nick Craver Feb 25 '10 at 13:16
  • 10
    It appears `ToUpper(Invariant)` is not only faster, but more reliable: http://stackoverflow.com/a/2801521/67824 – Ohad Schneider Jul 05 '14 at 13:14
  • @OhadSchneider it's more reliable *when comparing different languages* which doesn't really apply to this scenario - but yes, it's good to know for other cases (get it? "cases"? I'll see myself out). – Nick Craver Jul 05 '14 at 13:57
  • 5
    8 years later... https://twitter.com/Nick_Craver/status/970736005287264256 – fubo Mar 08 '18 at 12:34
64

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 reasons for this. For example, the Unicode standard allows text with diacritics to be encoded multiple ways. Some characters includes both the base character and the diacritic in a single code point. These characters may also be represented as the base character followed by a combining diacritic character. These two representations are equal for all purposes, and the culture-aware string comparisons in the .NET Framework will correctly identify them as equal, with either the CurrentCulture or the InvariantCulture (with or without IgnoreCase). An ordinal comparison, on the other hand, will incorrectly regard them as unequal.

Unfortunately, switch doesn't do anything but an ordinal comparison. An ordinal comparison is fine for certain kinds of applications, like parsing an ASCII file with rigidly defined codes, but ordinal string comparison is wrong for most other uses.

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. The list can be searched using the proper string comparison. When the match is found then the associated delegate may be invoked.

Another option is to do the obvious chain of if statements. This usually turns out to be not as bad as it sounds, since the structure is very regular.

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.

If there are many cases to be compared, and performance is an issue, then the List<T> option described above could be replaced with a sorted dictionary or hash table. Then the performance may potentially match or exceed the switch statement option.

Here is an example of the list of delegates:

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 and possibly a return type to the CustomSwitchDestination delegate. And you'll want to make better names!

If the behavior of each of your cases is not amenable to delegate invocation in this manner, such as if differnt parameters are necessary, then you’re stuck with chained if statments. I’ve also done this a few 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";
    }
Jeffrey L Whitledge
  • 53,361
  • 9
  • 64
  • 96
  • 6
    Unless I'm mistaken, the two are only different for certain cultures (like Turkish), and in that case couldn't he use `ToUpperInvariant()` or `ToLowerInvariant()`? Also, he's not comparing _two unknown strings_, he's comparing one unknown string to one known string. Thus, as long as he knows how to hardcode the suitable upper or lower case representation then the switch block should work fine. – Seth Petry-Johnson Feb 25 '10 at 13:38
  • 8
    @Seth Petry-Johnson - Perhaps that optimization could be made, but the reason the string comparison options are baked into the framework is so we don't all have to become linguistics experts to write correct, extensible software. – Jeffrey L Whitledge Feb 25 '10 at 13:45
  • 60
    OK. I'll give an example where this is relivant. Suppose instead of "house" we had the (English!) word "café". This value could be represented equally well (and equally likely) by either "caf\u00E9" or "cafe\u0301". Ordinal equality (as in a switch statement) with either `ToLower()` or `ToLowerInvariant()` will return false. `Equals` with `StringComparison.InvariantCultureIgnoreCase` will return true. Since both sequences look identical when displayed, the `ToLower()` version is a nasty bug to track down. This is why it's always best to do proper string comparisons, even if you're not Turkish. – Jeffrey L Whitledge Feb 25 '10 at 19:31
51

Sorry for this new post to an old question, but there is a new option for solving this problem using C# 7 (VS 2017).

C# 7 now offers "pattern matching", and it can be used to address this issue thusly:

string houseName = "house";  // value to be tested, ignoring case
string windowName;   // switch block will set value here

switch (true)
{
    case bool b when houseName.Equals("MyHouse", StringComparison.InvariantCultureIgnoreCase): 
        windowName = "MyWindow";
        break;
    case bool b when houseName.Equals("YourHouse", StringComparison.InvariantCultureIgnoreCase): 
        windowName = "YourWindow";
        break;
    case bool b when houseName.Equals("House", StringComparison.InvariantCultureIgnoreCase): 
        windowName = "Window";
        break;
    default:
        windowName = null;
        break;
}

This solution also deals with the issue mentioned in the answer by @Jeffrey L Whitledge that case-insensitive comparison of strings is not the same as comparing two lower-cased strings.

By the way, there was an interesting article in February 2017 in Visual Studio Magazine describing pattern matching and how it can be used in case blocks. Please have a look: Pattern Matching in C# 7.0 Case Blocks

EDIT

In light of @LewisM's answer, it's important to point out that the switch statement has some new, interesting behavior. That is that if your case statement contains a variable declaration, then the value specified in the switch part is copied into the variable declared in the case. In the following example, the value true is copied into the local variable b. Further to that, the variable b is unused, and exists only so that the when clause to the case statement can exist:

switch(true)
{
    case bool b when houseName.Equals("X", StringComparison.InvariantCultureIgnoreCase):
        windowName = "X-Window";):
        break;
}

As @LewisM points out, this can be used to benefit - that benefit being that the thing being compared is actually in the switch statement, as it is with the classical use of the switch statement. Also, the temporary values declared in the case statement can prevent unwanted or inadvertent changes to the original value:

switch(houseName)
{
    case string hn when hn.Equals("X", StringComparison.InvariantCultureIgnoreCase):
        windowName = "X-Window";
        break;
}
STLDev
  • 5,459
  • 21
  • 33
  • 2
    It would be longer, but I would prefer to `switch (houseName)` then do the comparison similar to the way to you did it, i.e. `case var name when name.Equals("MyHouse", ...` – LewisM Mar 07 '18 at 14:13
  • @LewisM - That's interesting. Can you show a working example of that? – STLDev Mar 07 '18 at 17:25
  • @LewisM - great answer. I've added further discussion on the assignment of `switch` argument values to `case` temporary variables. – STLDev Mar 12 '18 at 16:16
  • Yay for pattern matching in modern C# – Thiago Silva Jul 16 '19 at 00:06
  • You can also use "object pattern matching" like so `case { } when` so you don't have to worry about variable type and name. – Bob Apr 07 '20 at 13:27
36

In some cases it might be a good idea to use an enum. So first parse the enum (with ignoreCase flag true) and than have a switch on the enum.

SampleEnum Result;
bool Success = SampleEnum.TryParse(inputText, true, out Result);
if(!Success){
     //value was not in the enum values
}else{
   switch (Result) {
      case SampleEnum.Value1:
      break;
      case SampleEnum.Value2:
      break;
      default:
      //do default behaviour
      break;
   }
}
Bellash
  • 5,719
  • 3
  • 39
  • 72
uli78
  • 1,004
  • 1
  • 19
  • 27
26

An extension to the answer by @STLDeveloperA. A new way to do statement evaluation without multiple if statements as of c# 7 is using the pattern matching Switch statement, similar to the way @STLDeveloper though this way is switching on the variable being switched

string houseName = "house";  // value to be tested
string s;
switch (houseName)
{
    case var name when string.Equals(name, "Bungalow", StringComparison.InvariantCultureIgnoreCase): 
        s = "Single glazed";
    break;

    case var name when string.Equals(name, "Church", StringComparison.InvariantCultureIgnoreCase):
        s = "Stained glass";
        break;
        ...
    default:
        s = "No windows (cold or dark)";
        break;
}

The visual studio magazine has a nice article on pattern matching case blocks that might be worth a look.

LewisM
  • 769
  • 10
  • 19
  • Thank you for pointing out the additional functionality of the new `switch` statement. – STLDev Mar 12 '18 at 16:17
  • 6
    +1 - this should be the accepted answer for modern (C#7 onwards) development. One change I would make is that I would code like this: `case var name when "Bungalow".Equals(name, StringComparison.InvariantCultureIgnoreCase):` as this can prevent a null reference exception (where houseName is null), or alternatively add a case for the string being null first. – Jay May 04 '18 at 08:52
21

One possible way would be to use an ignore case dictionary with an action delegate.

string s = null;
var dic = new Dictionary<string, Action>(StringComparer.CurrentCultureIgnoreCase)
{
    {"house",  () => s = "window"},
    {"house2", () => s = "window2"}
};

dic["HouSe"]();

// Note that the call doesn't return text, but only populates local variable s.
// If you want to return the actual text, replace Action to Func<string> and values in dictionary to something like () => "window2"

Michael Freidgeim
  • 21,559
  • 15
  • 127
  • 153
Magnus
  • 41,888
  • 7
  • 70
  • 108
  • 4
    Rather than `CurrentCultureIgnoreCase`, [`OrdinalIgnoreCase`](https://msdn.microsoft.com/en-us/library/ms973919.aspx) is preferred. – Richard Ev Feb 26 '18 at 04:00
  • 2
    @richardEverett Preferred? Depends on what you want, if you want current culture ignore case it is not preferred. – Magnus Apr 22 '19 at 18:58
  • If anyone's interested, my solution (below) takes this idea and wraps it in a simple class. – Flydog57 Jul 30 '19 at 18:57
2

Here's a solution that wraps @Magnus 's solution in a class:

public class SwitchCaseIndependent : IEnumerable<KeyValuePair<string, Action>>
{
    private readonly Dictionary<string, Action> _cases = new Dictionary<string, Action>(StringComparer.OrdinalIgnoreCase);

    public void Add(string theCase, Action theResult)
    {
        _cases.Add(theCase, theResult);
    }

    public Action this[string whichCase]
    {
        get
        {
            if (!_cases.ContainsKey(whichCase))
            {
                throw new ArgumentException($"Error in SwitchCaseIndependent, \"{whichCase}\" is not a valid option");
            }
            //otherwise
            return _cases[whichCase];
        }
    }

    public IEnumerator<KeyValuePair<string, Action>> GetEnumerator()
    {
        return _cases.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _cases.GetEnumerator();
    }
}

Here's an example of using it in a simple Windows Form's app:

   var mySwitch = new SwitchCaseIndependent
   {
       {"hello", () => MessageBox.Show("hello")},
       {"Goodbye", () => MessageBox.Show("Goodbye")},
       {"SoLong", () => MessageBox.Show("SoLong")},
   };
   mySwitch["HELLO"]();

If you use lambdas (like the example), you get closures which will capture your local variables (pretty close to the feeling you get from a switch statement).

Since it uses a Dictionary under the covers, it gets O(1) behavior and doesn't rely on walking through the list of strings. Of course, you need to construct that dictionary, and that probably costs more.

It would probably make sense to add a simple bool ContainsCase(string aCase) method that simply calls the dictionary's ContainsKey method.

Flydog57
  • 4,634
  • 2
  • 12
  • 15
1

I hope this helps try to convert the whole string into particular case either lower case or Upper case and use the Lowercase string for comparison:

public string ConvertMeasurements(string unitType, string value)
{
    switch (unitType.ToLower())
    {
        case "mmol/l": return (Double.Parse(value) * 0.0555).ToString();
        case "mg/dl": return (double.Parse(value) * 18.0182).ToString();
    }
}
FormigaNinja
  • 1,560
  • 1
  • 24
  • 34
0

It should be sufficient to do this:

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

The switch comparison is thereby culture invariant. As far as I can see this should achieve the same result as the C#7 Pattern-Matching solutions, but more succinctly.

  • No it doesn't. As the top-voted answer explains, case-invariant comparison is *not* the same as comparing lowercase values. Besides, every string operation creates a *new* string, which results in a lot of wasted memory and CPU (for the allocations, GC). That's why it's preferable to use `Equals` with an `IgnoreCase` option. When processing even moderate amounts of data (eg crunching log files) avoiding such allocations can cause speed ups equivalent to using 2 or 3 extra cores – Panagiotis Kanavos Apr 22 '21 at 09:41