How to make C# switch statement use IgnoreCase?
Asked Answered
S

12

124

If I have a switch-case statement where the object in the switch is a 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?

Snowonthemountain answered 25/2, 2010 at 13:7 Comment(0)
H
72

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";
    }
Hermaherman answered 25/2, 2010 at 13:25 Comment(3)
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.Mika
@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.Hermaherman
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.Hermaherman
L
98

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;
}
Loo answered 25/2, 2010 at 13:8 Comment(7)
@Nick, do you have any reference to the reason for the performance difference between the lower and upper conversions? Not challenging it just curious.Chigetai
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?Snowonthemountain
@Chigetai - This is from CLR via C#, it was posted here a while back in the hidden features thread as well: https://mcmap.net/q/16352/-hidden-features-of-c-closed/… You can fire up LinqPad with a few million iterations, holds true.Loo
@Snowonthemountain - No, unfortunately there's not just because of it's static nature. There was a good batch of answers on this a while back: #45405Loo
It appears ToUpper(Invariant) is not only faster, but more reliable: https://mcmap.net/q/182095/-what-is-wrong-with-tolowerinvariantPictor
@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).Loo
8 years later... twitter.com/Nick_Craver/status/970736005287264256Bordelon
L
84

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;
}
Longueur answered 9/6, 2017 at 1:38 Comment(5)
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", ...Examen
@Examen - That's interesting. Can you show a working example of that?Longueur
@Examen - great answer. I've added further discussion on the assignment of switch argument values to case temporary variables.Longueur
Yay for pattern matching in modern C#Hydromancy
You can also use "object pattern matching" like so case { } when so you don't have to worry about variable type and name.Nakasuji
H
72

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";
    }
Hermaherman answered 25/2, 2010 at 13:25 Comment(3)
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.Mika
@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.Hermaherman
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.Hermaherman
E
51

An extension to the answer by @STLDev.

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 @STLDev 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.

Examen answered 8/3, 2018 at 16:4 Comment(4)
Thank you for pointing out the additional functionality of the new switch statement.Longueur
+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.Chow
@Chow Passing null into the switch above wouldn't create a NRE.Pitchford
@Pitchford - Look at the edit history - when I posted that comment (3 years ago), the example code would have caused a NullReferenceException. The example code has since been changed by someone.Chow
P
38

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;
    }
}
Presto answered 30/5, 2011 at 11:55 Comment(2)
Just a Note : Enum TryParse seems to be available with Framework 4.0 and forward, FYI. msdn.microsoft.com/en-us/library/dd991317(v=vs.100).aspxAry
I prefer this solution as it discourages the use of magic strings.Rumilly
D
24

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"

Doyle answered 15/5, 2014 at 15:7 Comment(3)
Rather than CurrentCultureIgnoreCase, OrdinalIgnoreCase is preferred.Medford
@richardEverett Preferred? Depends on what you want, if you want current culture ignore case it is not preferred.Doyle
If anyone's interested, my solution (below) takes this idea and wraps it in a simple class.Innovation
I
11

I would say that with switch expressions (added in C# 8.0), discard patterns and local functions the approaches suggested by @STLDev and @LewisM can be rewritten in even more clean/shorter way:

string houseName = "house";  // value to be tested
// local method to compare, I prefer to put them at the bottom of the invoking method:
bool Compare(string right) => string.Equals(houseName, right, StringComparison.InvariantCultureIgnoreCase);
var s = houseName switch
{
    _ when Compare("Bungalow") => "Single glazed",
    _ when Compare("Church") => "Stained glass",
    //  ...
    _ => "No windows (cold or dark)" // default value
};
Ilo answered 27/6, 2022 at 16:37 Comment(3)
IMO best solution, it is clean, compact & readable!Disconsolate
It is dangerous IMHO that the Compare function references houseName hard-coded. When reading, one might think that the houseName from the switch expression is compared to "Bungalow" and so on (I thought this first), but you can actually pass any variable you like, it is just ignored.Scarabaeoid
@Scarabaeoid yes, possibly. Version which accepts two parameters would not be that different.Ilo
S
10

Now you can use the switch expression (rewrote the previous example):

return houseName switch
{
    _ when houseName.Equals("MyHouse", StringComparison.InvariantCultureIgnoreCase) => "MyWindow",
    _ when houseName.Equals("YourHouse", StringComparison.InvariantCultureIgnoreCase) => "YourWindow",
    _ when houseName.Equals("House", StringComparison.InvariantCultureIgnoreCase) => "Window",
    _ => null
};
Sympathizer answered 7/1, 2023 at 20:37 Comment(2)
Cool, used the described switch principles in a factory classChuffy
lol just use if case with ? and :Glennglenna
I
4

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. If you want to reuse the Switch behavior over and over, you can create and initialize the the SwitchCaseIndependent object once and then use it as many times as you want.

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

Innovation answered 10/8, 2018 at 22:24 Comment(0)
E
3

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.

Elliotelliott answered 28/5, 2020 at 5:2 Comment(1)
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 coresAntiserum
K
1

Try to convert the whole string into a particular case, either lower case or upper case, and then use it 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();
    }
}
Kruger answered 22/5, 2015 at 5:41 Comment(0)
F
0

Using the Case Insensitive Comparison: Comparing strings while ignoring case.

switch (caseSwitch)
{
    case string s when s.Equals("someValue", StringComparison.InvariantCultureIgnoreCase):
        // ...
        break;
}

for more detail Visit this link: Switch Case When In C# Statement And Expression

Franchot answered 6/12, 2022 at 8:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.