Monday 17 September 2007

Enum

inspired by Enum, here's my version... it still needs to work with resources, but works otherwise.


public static class Enum <T>
{

public static T Parse ( string name )
{
return ( T ) Enum.Parse ( typeof ( T ), name );
}

public static IEnumerable < T > GetValues ( )
{
foreach ( T value in Enum.GetValues ( typeof ( T ) ) )
{
yield return value;
}
}


public static IEnumerable<AttributeType> GetAttributes <AttributeType> ( T value ) where AttributeType : Attribute
{
FieldInfo fieldInfo = typeof ( T ).GetField ( value.ToString ( ) );


if (fieldInfo != null)
{
foreach ( object customAttribute in fieldInfo.GetCustomAttributes ( typeof ( AttributeType ), false ) )
{
yield return customAttribute as AttributeType;
}
}
}

public static IList<AttributeType> GetAttributeList <AttributeType> ( T value ) where AttributeType : Attribute
{
return new List<AttributeType> ( GetAttributes<AttributeType> ( value ) );
}

public static string GetDescription( T value )
{
IList< DescriptionAttribute > attributeList = GetAttributeList<DescriptionAttribute> ( value );

if (attributeList.Count < 1)
return value.ToString();

return attributeList[ 0 ].Description;
}
}

No comments: