• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 123
  • Last Modified:

Dynamically assign enumeration selection from variable

Hi, I'm pretty new at using enumerators.  I would set the value of the enumerator based on a value set in a database table.  Below is a simplified attempt to show what I'm trying to do ... I'm open to any methods to do this, doesn't have to be a switch.  I am also getting an error on the 2nd RouteMethod saying: a local variable name 'RouteMethod' is already defined in this scope.

static string method1()

//value from database
String RM = dbConfig("RouteMethod").ToString();
            switch (RM)
            {
                case "Practical":
                    RouteType RouteMethod = RouteType.Practical;
                    break;
                case "Shortest":
                    RouteType RouteMethod = RouteType.Shortest;
                    break;
                case "National":
                    RouteType RouteMethod = RouteType.National;
                    break;
                case "FiftyThree":
                    RouteType RouteMethod = RouteType.FiftyThree;
                    break;
                case "AvoidToll":
                    RouteType RouteMethod = RouteType.AvoidToll;
                    break;
                case "Air":
                    RouteType RouteMethod = RouteType.Air;
                    break;
                default:
                    RouteType RouteMethod = RouteType.Practical;
                    break;
            }   

Open in new window

0
Scarlett72
Asked:
Scarlett72
1 Solution
 
Russ SuterCommented:
Your enum declaration is missing from the example but I'm assuming it's something like this:

public Enum RouteType
{
  Practical,
  Shortest,
  National,
  FiftyThree,
  AvoidToll,
  Air
}

Open in new window


If that's the case then they have integer values starting with zero. Store your value in your database as an int and do a simple cast on the way out.

RouteType RouteMethod = (RouteType)Convert.ToInt32(dbConfig("RouteMethod"))

Open in new window


If you really want to store as a string (which does make it easier to read in the database you could cast it like this:

(RouteType)Enum.Parse(typeof(RouteType), dbConfig("RouteMethod").toString());

Open in new window

0
 
Scarlett72Author Commented:
Thank you Russ that worked!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now