Wednesday, February 17, 2010

Enum Extensions

If you're a fan of Enums for readability in an application here are some resources for making them more usable.
The first item is used for places where you'd like some enum values to have a space in the name when displayed somewhere. You can use System.ComponentModel.DescriptionAttribute like so:

       [Flags]
       public enum PermissionType
       {

           Select = 1,
           Insert = 2,
           Update = 4,
           Delete = 8,
           Alter = 16,
           Execute = 32,
           [
Description("View Definition")]
           ViewDefinition = 64
       }
 
and here's the extension method to make it easily usable:
 
    using System.ComponentModel;
 
    /// from: http://www.moggoly.me.uk/blog/post/Enum-description-values.asp
    public static string DescriptionOrToString(this T value)
    {

        
var da = (DescriptionAttribute[])(typeof(T).GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false));

        
return da.Length > 0 ? da[0].Description : value.ToString();

    }

if you don't like the possible clutter of having every object have a DescriptionOrToString in your intellisense, change the signature to
 
public static string DescriptionOrToString(this T value) where T:struct

This method is for enumerating enum values that are used as [Flags] (where a single value can contain many different values in the same enum)

    
///
    /// Gets all combined items from an enum value.
    /// from: http://stackoverflow.com/questions/105372/c-how-to-enumerate-an-enum
    ///
    ///
    /// The value.
    ///
    public static IEnumerable GetAllSelectedItems(this Enum value)
    {
        
int valueAsInt = Convert.ToInt32(value, CultureInfo.InvariantCulture);

        
foreach (object item in Enum.GetValues(typeof(T)))
        {
            
int itemAsInt = Convert.ToInt32(item, CultureInfo.InvariantCulture);

            
if (itemAsInt == (valueAsInt & itemAsInt))
            {
                
yield return (T)item;
            }
        }
    }

The next post will contain a usage example for GetAllSelectedItems.

No comments:

Post a Comment