Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using properties in switch statement cases?

I have a switch statement in one class that generates Command objects, based on if a certain line in a code file matches the particular code for that Command object.

like this:

switch (line):
{
   case "#CODE1":
      return new Command1();
   case "#CODE2":
      return new Command2();
}

I want to turn it into something like this:

switch (line):
{
   case Command1.Code:
      return new Command1();
   case Command2.Code:
      return new Command2();
}

I tried it by creating a public static property of Command1, but the compiler complains...

Is there a way to do something along this intent, that the compiler won't complain about?

like image 454
Alex Baranosky Avatar asked Aug 04 '26 14:08

Alex Baranosky


1 Answers

I think you can do this only with constants... so if it's possible for you, use constant fields instead of public static properties. The difference is that it's treated like a literal at compile time, so if the value changes, you would need to recompile all assemblies that reference the constant.

like image 124
Botz3000 Avatar answered Aug 06 '26 04:08

Botz3000