Enums used to leave a bad taste in my mouth. Mostly because it didn’t support spaces in the enum names. For that reason if I always wanted to do simple name value lookup, I would use strings instead of enums.

But things have changed. Now, using a handy description attribute, you can describe enums with spaces in their names and look them up like any other string.

enum DocumentCategory
{
       Debit = 1,
       Credit = 2,
       [Description("N/A")]
       NotApplicable = 3
}

And then you can access and look things up with:

Enum.GetValues(typeof (DocumentCategory));
int id = (int) DocumentCategory.Debit;
string code = DocumentCategory.Debit.ToString();
var debitEnum = Enum.Parse(typeof (DocumentCategory), "Debit");

I realize this has been around for a while. I am just slow picking up on this kind of stuff. Thanks to Ghassan Karwchan for pointing this out to me.

This is how I used to do it (old school):

    public class DocumentCategory : BaseLookup<DocumentCategory>
    {
        public static DocumentCategory Debit = new DocumentCategory(1, "Debit");
        public static DocumentCategory Credit = new DocumentCategory(2, "Credit");
        public static DocumentCategory NotApplicable = new DocumentCategory(3, "N/A");

        private DocumentCategory(int id, string name) : base(id, name) { }        
    }

    public abstract class BaseLookup<T> where T: BaseLookup<T> 
    {
        protected int id;
        protected string name;

        protected BaseLookup(int id, string name)
        {
            this.id = id;
            this.name = name;
        }

        protected BaseLookup()
        {
        }
        
        public int Id
        {
            get { return id; }
        }

        public string Name
        {
            get { return name; }
        }

        public static List<T> List()
        {
            return typeof (T)
                .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)
                .Select(property => property.GetValue(typeof (T)) as T).ToList();
        }

        public static int LookupId(string name)
        {
            var lookup = List().Where(lkp => lkp.name == name).FirstOrDefault();
            return lookup == null ? 0 : lookup.id;

        }

        public static string LookupName(int id)
        {
            var lookup = List().Where(lkp => lkp.id == id).FirstOrDefault();
            return lookup == null ? string.Empty : lookup.name;
        }

    }