Switch statement with static fields

I know this is an old question but there is a way that wasnt covered in the other answers that doesnt involve changing the approach:

switch(pid)
{
   case var _ when pid == PID_1:
      //Do something 1
   break;
}

It looks like those string values should simply be constant.

public const string PID_1 = "12";
public const string PID_2 = "13";
public const string PID_3 = "14";

If that's not an option (they are actually changed at runtime), then you can refactor that solution into a series of if/else if statements.

As to why the case statements need to be constant; by having them be constant it allows the statement to be much more heavily optimized. It is actually more efficient than a series of if/else if statements (although not dramatically so if you don't have lots of conditional checks that take a long time). It will generate the equivalent of a hash table with the case statement values as keys. That approach couldn't be used if the values can change.


... C# doesn't allow non-const statement inside switch...

If you can't use:

public const string PID_1 = "12";
public const string PID_2 = "13";
public const string PID_3 = "14";

You can use a dictionary :)

....
public static string PID_1 = "12";
public static string PID_2 = "13";
public static string PID_3 = "14";



// Define other methods and classes here

void Main()
{
   var dict = new Dictionary<string, Action>
   {
    {PID_1, ()=>Console.WriteLine("one")},
    {PID_2, ()=>Console.WriteLine("two")},
    {PID_3, ()=>Console.WriteLine("three")},
   };
   var pid = PID_1;
   dict[pid](); 
}