How to make C# Switch Statement use IgnoreCase

后端 未结 10 1099
孤独总比滥情好
孤独总比滥情好 2020-11-27 16:56

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 =         


        
10条回答
  •  眼角桃花
    2020-11-27 17:26

    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;
    }
    

提交回复
热议问题