Red Swan
Red Swan

Reputation: 15545

how to make switch statement generic in c#

I want to use switch statement in c#. but instead of using a constant in the case expression I want to use an enumeration value. How do I use this. If i try to use it like:

 string strPageMode=...//some value;
 switch (strPageMode)
 {
     case ModesEnum.SystemHealth:
     //some code
     break;
}

giving error. what have to use then ? I don't want to use If statement.

Upvotes: 0

Views: 1376

Answers (5)

Lasse Espeholt
Lasse Espeholt

Reputation: 17782

If it is a string then this will work:

ModesEnum res;

//Implicit generic as opposed to Enum.Parse which returns object
Enum.TryParse(strPageMode, out res); //returns false if parsing failed

switch (res)
{
    case ModesEnum.SystemHealth:
        break;
}

As noted, the generic TryParse is not available in < .Net 4.0. Otherwise, use the Enum.Parse.

Upvotes: 5

Jon Hanna
Jon Hanna

Reputation: 113242

An enumeration literal (rather than the current value of a variable of that enumeration type) is a constant.

There is a specific sense of the word "generic" in .NET and a general sense in English. I don't understand what this has to do with either.

Based on the quasi-Hungarian name I'm guessing that strPageMode is a string (please tell me you don't really name variables like that in C# code). Considering switch as a sort of syntactic sugar for a set of if-else statements, this means you are doing an equality comparison between a string and an enum. If this were allowed it would be rather pointless, as the string being a string and the enum being an enum, they are inherently never going to be equal whatever their values are.

You need to either parse the string into a ModesEnum value, and use that in the switch statement, or else make the case values strings with ModesEnum.SystemHealth.ToString().

Upvotes: 1

VJOY
VJOY

Reputation: 3792

In one of my projects, I have used switch case in the similar manner.

switch(UserType)
{
   case User.Guest:
            break;
}

Here UserType is a string and User is enum. It worked for me.

Upvotes: 0

Tim Jones
Tim Jones

Reputation: 1786

Assuming that strPageMode represents the name of one possible value of ModesEnum, you could do this:

switch (Enum.Parse(typeof(ModesEnum), strPageMode, false))
{
    ... as before
}

Upvotes: 2

&#181;Bio
&#181;Bio

Reputation: 10748

How is strPageMode declared? It needs to be an instance of ModesEnum, I'm guessing it is a string.

Upvotes: 3

Related Questions