Wednesday, September 06, 2006

.NET: tricky enums with custom attributes

Sometimes, when we want to serialize data type we use attributes to give additional description for type itself and its fields.

Imagine that the type we want to serialize has enum field (SampleEnum)


public class ExtendedInfoAttribute : Attribute
{
string description;

public string Description
{
get { return description; }
set { description = value; }
}

}



public enum SampleEnum
{
[ExtendedInfo(Description="First value")]
EnumValueOne,
[ExtendedInfo(Description = "Second value")]
EnumValueTwo
}



ExtendedInfo attribute provides additional info about enum fields. When serializing this attribute value can be used to provide some additional info about enum fields.


So, what's so special about getting these attribute values? Well, nothing special if you known where to look for :8-)

//errors checking is omitted for clarity
SampleEnum sEnum = SampleEnum.EnumValueTwo;

Type type = sEnum.GetType();
FieldInfo fieldInfo = type.GetField(Enum.GetName(type, sEnum));
ExtendedInfoAttribute[] attrs = (ExtendedInfoAttribute[])fieldInfo.GetCustomAttributes(
typeof(ExtendedInfoAttribute), false);
Console.WriteLine(attrs[0].Description);

2 comments:

  1. Thanks - was looking for exactly this!

    ReplyDelete
  2. Anmutig topic viagra online cialis rezeptfrei [url=http//t7-isis.org]cialis 5mg[/url]

    ReplyDelete