user3352250
user3352250

Reputation: 326

How to get a collection of values as an enum?

I am creating a library that will be used as an API to work with a specific website. I have a list of states and cities with their corresponding IDs on the website.

The list of states and their list of cities must be accessible in design-mode (A developer should be able to access the list without compiling). I did this by creating a static class with static variables.

Here is how it looks.

    public class States
    {
       public static readonly States Arizona = new States(451, "Arizona", "lat", "lon");
       //many of these here

       public States(int key, string value, string lat, string lon, Cities cities)
       {
        this.Key = key;
        this.Name = value;
        this.Latitude = lat;
        this.Longitude = lon;
        this.Cities = cities;
       }
    }
    public class Cities
    {
       public static readonly Cities Phoenix = new States(1, States.GetById(451), "Phoenix", "lat", "lon");

       public Cities(int key, States state, string value, string lat, string lon)
       {  
        this.Key = key;
        this.Name = value;  
        this.State = state;
        this.Latitude = lat;
        this.Longitude = lon;
       }
    }

It will be used as: var x = States.Arizona.Phoenix.Key;

So. When getting a specific enum via States.GetById() - everything is fine. But.. how should I make the same thing for States.Cities? It definately should be a collection, but then the user (developer) will not have the ability to select a specific city without calling a "look up by name" function or something.

I could do a separate class for each state... But that just sounds like a really really wrong way to do it. What is the right way to do this?

Upvotes: 1

Views: 266

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157126

Indeed, you need to have a separate class for each state, usually deriving a base class to get the standard methods, properties, etc.

The problem you face then is typically a code generation issue. You want to have a bunch of code, with as least as effort as possible. We generate a database model to c# code and we find XSLT useful for this. We have an XML file with all the values (extracted by another tool), and an XSLT that transforms that to classes.

Upvotes: 2

Related Questions