0

I'd like to use a small array of strings in the same way I use Enums. I'd like to

  1. Limit the possible property values to these preset options
  2. Have intelisence display those options
  3. Share this 'OptionList' with other objects in my project

Here's what I currently have:

public enum StatusOptions
{
        OptionOk = 1, OptionDisabled = 0
}

public class User()
{
        public StatusOptions Status { get; set; }
}

Here's what I'd like to do - but can't because Enums are limited to int

public string[] StatusOptions
{
        "ok", "disabled"
}

public class User()
{
        public StatusOptions Status { get; set; }
}

What is the Best way of doing this?

ActionFactory
  • 1,393
  • 2
  • 12
  • 19
  • There is a smart solution in CodeProject that could help you: http://www.codeproject.com/Articles/11130/String-Enumerations-in-C – GoRoS Sep 23 '12 at 11:55

2 Answers2

4

You can use the DescriptionAttribute with enumeration values - when you need to get the string you can use reflection to retrieve the value of this attribute.

public enum StatusOptions
{
        [Description("ok")]
        OptionOk = 1, 
        [Description("disabled")]
        OptionDisabled = 0
}
Joundill
  • 6,828
  • 12
  • 36
  • 50
Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

Refer to this C# String enums

This should satisfy most of your conditions:

public sealed class StatusOptions {

    private readonly int value;
    public int Value
    {
     get{ return value;}
    }

    private readonly string desc;
    public string Description
    {
     get{ return desc;}
    }

    public static readonly StatusOptions OptionDisabled  = new StatusOptions (0,"Disabled");
    public static readonly StatusOptions OptionOk   = new StatusOptions (1, "Ok");

    private StatusOptions(int value, string desc){
        this.value = value;
            this.Description = desc;
    }

}

Usage:

StatusOptions s1 = StatusOptions.OptionOk;
int val = s1.Value;
string desc = s1.Description;
Community
  • 1
  • 1
prashanth
  • 2,059
  • 12
  • 13