Home > Mobile >  C# switch case with constant values as case condition
C# switch case with constant values as case condition

Time:05-31

I am using C# (8.0) switch statement as shown here:

var operation = 2;  

var result = operation switch  
{  
    1 => "Case 1",  
    2 => "Case 2",  
    3 => "Case 3",  
    4 => "Case 4",  
    _ => "No case available"  
};  

I would like to check if we can apply some constant variable which will has some values in it to match with case condition - for example:

public static readonly string operation1 = "1";
public static readonly string operation2 = "2";

var result = operation switch  
{  
    operation1  => "Case 1",  
    operation2  => "Case 2",  
    _ => "No case available"  
};  

Kindly let me know if there is any better way to handle this I don't want to hard code the values in the switch statement as per standards and we maintain the constants in one place and referring to them in the projects at different sections

CodePudding user response:

Using the nameof operator can help a great deal. To follow your post as closely as possible, suppose you make a class with methods operation1 and operation2. When you call them, a C# (8.0) switch statement supplies the appropriate Run message.

using System.Reflection;
using System.Runtime.CompilerServices;

var myClass = new MyClass();
myClass.operation1();
myClass.operation2();

class MyClass
{
    public void operation1() 
    {
        ShowRunMessage();
    }
    public void operation2()
    {
        ShowRunMessage();
    }

    private void ShowRunMessage([CallerMemberName] string? name = null)
    {
        // C# (8.0) switch statement
        var result = name switch
        {
            nameof(operation1) => "Case 1",
            nameof(operation2) => "Case 2",
            _ => throw new NotImplementedException(),
        };
        Console.WriteLine($"'{name}' produces {result}");
    }
}

Console out before

If you now decide to refactor the method names the switch isn't going to break. The switch code does not need to be touched at all (definitely not the global string replace that we started out with).

Refactor

The output is still correct:

Console out after

Another Example

Occasionally I find it's handier to switch on a Type name than to break it out with is blocks.

private void SwitchOnType(object unk)
{            
    // C# (8.0) switch statement
    var result = unk.GetType().Name switch
    {
        nameof(TypeA) => "Case 1",
        nameof(TypeB) => "Case 2",
        _ => throw new NotImplementedException(),
    };

    // (Is sometimes a handy alternative to...)
    if(unk is TypeA typeA){ }
    else if (unk is TypeB typeB){ } 
    // ...
}

CodePudding user response:

Constant expression can be used in switch statement/expression directly via constant pattern:

const string operation1 = "1";
const string operation2 = "2";

var result = operation switch  
{  
    operation1  => "Case 1",  
    operation2  => "Case 2",  
    _ => "No case available"  
}; 

But if it is a variable and not a constant then var pattern with case guards can be used instead:

var operation1 = "1";
var operation2 = "2";

var result = operation switch  
{  
    var c1 when c1 == operation1  => "Case 1",  
    var c2 when c2 == operation2  => "Case 2",  
    _ => "No case available"  
}; 
  • Related