Search code examples
c#stringswitch-statement

How can I use a modified String in a C# switch → case statement?


I have a string I need to use, a variant of, in many places throughout my application. For example:

String myString = "The Quick Brown Fox";

string someLowerCaseString = myString.ToLower();
string someUpperCaseString = myString.ToUpper();
string someOtherNewString = myString.Replace(' ','+');

I have this String in a Constants.cs file that I reference throughout the application. I have tried two different approaches:

public const String myString = "The Quick Brown Fox";
public static readonly String myString = "The Quick Brown Fox";

However, when I try to "manipulate" the string for use in a switchcase statement, I cannot get it to work:

switch(some_value){
    case Constants.myString.ToLower():
    case Constants.myString.ToUpper():
    case Constants.myString.Replace(' ','+'):
}

I get the error:

CS0426: The type name 'myString' does not exist in the type 'Constants'

I have even tried this:

String localString = Constants.myString.ToLower();
String localString = Constants.myString.ToUpper();
String localString = Constants.myString.Replace(' ','+');
const String localString = Constants.myString.ToLower();
const String localString = Constants.myString.ToUpper();
const String localString = Constants.myString.Replace(' ','+');
switch(some_value){
    case localString:
}

And that does not work either. I get the error:

CS9135: A constant value of type 'string' is expected

I cannot use this:

switch(value.ToLower()){
    // ...
}

As sometimes I need the first letter capitalized and sometimes I need all letters upper/lowercase.

The official Microsoft C# documentation says that these modifying methods return a copy of the string, so I didn't think I was actually manipulating the String constant.


Solution

  • Try this:

    using System;
    
    namespace CSharpTests
    {
        internal class Constants
        {
            public const String myString = "The Quick Brown Fox";
        }
    
        internal class Program
        {
            static void Main(string[] args)
            {
                String some_value = Constants.myString.ToLower();
                
                switch (some_value)
                {
                    case string s when s == Constants.myString.ToUpper():
                        Console.WriteLine("Is upper");
                        break;
                    case string s when s == Constants.myString.ToLower():
                        Console.WriteLine("Is lower");
                        break;
                    case string s when s == Constants.myString.Replace(' ', '_'):
                        Console.WriteLine("Is replaced");
                        break;
                    default:
                        Console.WriteLine("None of the cases");
                        break;
                }
            }
        }
    }