Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Switch on enums

Tags:

c#

asp.net

I have an enum:

public enum Status 
{ 
    Incomplete = 1, Complete = 2, Cancelled = 3, Deleted = 4 
}

Now on a certain page I wish to list this enum in a checkboxlist. This would be fine except that I want the text of each checkbox to display different text than the enum.

i.e the check boxes should say:

"Not Processed" instead of "Incomplete"

"Processed" instead of "Complete"

"Void" instead of "Cancelled"

Is it possible to put this enum in a foreach and then switch on the status and update the text. Like so:

var statuses = Enum.GetNames(typeof(Status));
foreach (var status in statuses)))
{
    switch (status)
    {
        case Status.Complete.ToString(): 
        status = "Processed";
        break; ...etc                 
    }
}

Any ideas would be greatly appreciated.

like image 547
Riain McAtamney Avatar asked Jul 02 '10 13:07

Riain McAtamney


2 Answers

C# has a language feature that directly addresses your question. Here's an article that gives you the complete details.

The short version: apply extension attribute values to each value:

enum OrderStatus  
{  
    [EnumValueData(Name="New Order")]  
    NewOrder = 1,  
    [EnumValueData(Name="In Process")]  
    Processing = 2,  
    [EnumValueData(Name="Shipped")]  
    Shipped = 3  
}  

Then apply said values to your radio-buttons, listbox or whatever:

public static Dictionary<int, string> GetListItems(Type enumType)  
{  
    if (!enumType.IsEnum)  
        throw new ApplicationException("GetListItems does not support non-enum types");  
    Dictionary<int, string> list = new Dictionary<int, string>();  
    foreach(FieldInfo field in enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public))  
    {  
        int value;  
        string display;  
        value = (int)field.GetValue(null);  
        display = Enum.GetName(enumType, value);  
        foreach(Attribute currAttr in field.GetCustomAttributes(true))  
        {  
            EnumValueDataAttribute valueAttribute = currAttr as EnumValueDataAttribute;  
            if (valueAttribute != null)  
                display = valueAttribute.Name;  
        }  
        list.Add(value, display);  
    }  
    return list;  
}  
like image 56
Bob Kaufman Avatar answered Oct 18 '22 06:10

Bob Kaufman


You can use the Description attribute in the System.ComponentModel class to assign a text description to each enum value. You can then set the text property by iterating through the enum and getting the Description attribute of each instead of using a switch.

public enum Status
{
    [Description("Not Processed")] Incomplete = 1,
    [Description("Processed")] Complete = 2,
    [Description("Void")] Cancelled = 3,
    Deleted = 4
}

You could then use something like the following to get the description of a single enum value (or modify it to return a Dictionary of as Bob showed in his example):

    public static string GetEnumDescription ( Object value )
    {
        try
        {
            Type objType = value.GetType();
            FieldInfo fldInf = objType.GetField( Enum.GetName( objType, value ) );

            Object[ ] attributes = fldInf.GetCustomAttributes( false );

            if ( attributes.Length > 0 )
            {
                DescriptionAttribute descAttr = ( DescriptionAttribute )attributes[ 0 ];
                return descAttr.Description;
            }
            else
            {
                return value.ToString();
            }
        }
        catch
        {
            return string.Empty;
        }
    }
like image 23
TLiebe Avatar answered Oct 18 '22 05:10

TLiebe