Alex Rivera | Logout

Enumerate with return type other than string?

Asked 2009-07-08T10:48:27.130
30

Since enumeration uses integers, what other structure can I use to give me enum-like access to the value linked to the name:

[I know this is wrong, looking for alternative]

private enum Project
    {
        Cleanup = new Guid("2ED3164-BB48-499B-86C4-A2B1114BF1"),
        Maintenance = new Guid("39D31D4-28EC-4832-827B-A11129EB2"),
        Upgrade = new Guid("892F865-E38D-46D7-809A-49510111C1"),
        Sales = new Guid("A5690E7-1111-4AFB-B44D-1DF3AD66D435"),
        Replacement = new Guid("11E5CBA2-EDDE-4ECA-BDFD-63BDBA725C8C"),
        Modem = new Guid("6F686C73-504B-111-9A0B-850C26FDB25F"),
        Audit = new Guid("30558C7-66D9-4189-9BD9-2B87D11190"),
        Queries = new Guid("9985242-516A-4151-B7DD-851112F562")
    }

EDIT 2014-07-20

This is a newer answer to this question. Using the Attribute class with a helper method, define the extra attributes needed on your enum.

 public enum MultiValueEnum
    {
        [FooAttribute("alpha", 20d, true)]
        First,
        [FooAttribute("beta", 40.91d, false)]
        Second,
        [FooAttribute("gamma", 1.2d, false)]
        Third,
    }     

  public class FooAttribute : Attribute
            {
                internal FooAttribute(string name, double percentage, bool isGood)
                {
                    this.Name = name;
                    this.Percentage = (decimal)percentage;
                    this.IsGood = isGood;
                }
                public string Name { get; private set; }
                public decimal Percentage { get; private set; }
                public bool IsGood { get; private set; }
            }



  public static TAttribute GetAttribute<TAttribute>(this Enum value)
        where TAttribute : Attribute
        {
            var type = value.GetType();
            var name = Enum.GetName(type, value);
            return type.GetField(name)
                .GetCustomAttributes(false)
                
Edit
Report

1 Answer

0

The enum type can only support the integral types (except char) as its value. You could however use something like a Dictionary to do lookups of a a name to a value.

Dictionary<Guid> lookup = new Dictionary<Guid>();
lookup["Cleanup"] = new Guid("2ED3164-BB48-499B-86C4-A2B1114BF1");
lookup["Maintenance"] = new Guid("39D31D4-28EC-4832-827B-A11129EB2");
lookup["Upgrade"] = new Guid("892F865-E38D-46D7-809A-49510111C1");
// etc...

Another alternative is to have a series of readonly values in a static class.

public static class Guids
{
  public static readonly Guid Cleanup = new Guid("2ED3164-BB48-499B-86C4-A2B1114BF1");
  public static readonly Guid Maintenance = new Guid("39D31D4-28EC-4832-827B-A11129EB2");
  public static readonly Guid Upgrade = new Guid("892F865-E38D-46D7-809A-49510111C1");
}
answered 2009-07-08T10:58:10.480

Your Answer