Suppose I have a bunch of static fields and I want to use them in switch:
public static string PID_1 = "12";
public static string PID_2 = "13";
public static string PID_3 = "14";
switch(pid)
{
case PID_1:
//Do something 1
break;
case PID_2:
//Do something 2
break;
case PID_3:
//Do something 3
break;
default:
//Do something default
break;
}
Since C# doesn't allow non-const statement inside switch. I want to understand what is the intention of this kind of design. How should I do something like above in c#?
The canonical way to approach this -- if your static fields are not actually constants -- is to use a
Dictionary<Something, Action>
:Case argument should be constant on compile-time.
Try to use
const
instead:It looks like those string values should simply be constant.
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.
I'm assuming there's a reason you didn't declare those variables as
const
. That said:The
switch
statement is just shorthand for a bunch ofif / else if
statements. So if you can guarantee thatPID_1
,PID_2
, andPID_3
will never be equal, the above is equivalent to this:... C# doesn't allow non-const statement inside switch...
If you can't use:
You can use a dictionary :)
Why you don't use enum ?
Enum keyword:
http://msdn.microsoft.com/en-us/library/sbbt4032%28v=vs.80%29.aspx
In your case it can be easily handled over enum: