views:

71

answers:

2

I'm working on this project and I have a large number of "services" to execute. I need to have this service codes so I can verifiy and make decisions according to selected services by it's code.

I'm tring to define this enum and get its values from the web.config so I can change them easily.

public enum ServiceCodes
{
    Transfer= Convert.ToInt32(ConfigurationManager.AppSettings["servTransfer"]),
    ChangePlate= Convert.ToInt32(ConfigurationManager.AppSettings["servChangePlate"])
}

But I get this error: The expression must be constant. (because of the Conversion)

What can I do? (Or you can suggest me totally different approaches.)

+2  A: 

Just go ahead and define a static class like this:

public static class ServiceCodes
{
  readonly static int Transfer = Convert.ToInt32(ConfigurationManager.AppSettings["servTransfer"])
  //...
}
the_drow
+3  A: 

The documentation states that enum values are constant. An alternative approach is to declare a class with static readonly members.

If you still need the type safety provided by an enum, you could use a slightly complex approach:

public class ServiceCodes {

    public static readonly ServiceCodes Transfer = new ServiceCodes(Convert.ToInt32(ConfigurationManager.AppSettings["servTransfer"]));
    public static readonly ServiceCodes ChangePlate = new ServiceCodes(Convert.ToInt32(ConfigurationManager.AppSettings["servChangePlate"]));

    internal int Code {get; private set;}

    private ServiceCodes(int code) {
        Code = code;
    }
}

Then, a method like:

public void SomeAction(ServiceCodes serviceCode) {
    //....  
}

could be called like this:

SomeAction(ServiceCodes.Transfer);

But, given the complexity (compared with the gain), I would go with the first approach.

Fernando