Anybody know what the best to use to read a XmlEnumAttribute
Option 1: With GetMember
public static string XmlEnum(this Enum e)
{
Type type = e.GetType();
MemberInfo[] memInfo = type.GetMember(e.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(XmlEnumAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((XmlEnumAttribute)attrs[0]).Name;
}
}
return e.ToString();
}
Option 2: With GetField
public static string XmlEnum2(this Enum e)
{
Type type = e.GetType();
FieldInfo info = type.GetField(e.ToString());
if (!info.IsDefined(typeof(XmlEnumAttribute), false))
{
return e.ToString();
}
object[] attrs = info.GetCustomAttributes(typeof(XmlEnumAttribute), false);
return ((XmlEnumAttribute)attrs[0]).Name;
}
Because that doesn’t test a realistic usage scenario for an attribute. It is expensive the first time you dig up an attribute, cheap after that. The expense is loading the IL for the attribute class and compiling it, locating the attribute data in the assembly metadata and loading it from disk. Then calling the attribute constructor and assigning the attribute properties. The cost of your code to read the attribute is peanuts compared to that, it’s the disk I/O that’s expensive by several orders of magnitude. The second time you retrieve the attribute, a lot of that work is done and it will be quick, just the object initialization from data that’s cached.
You normally read an attribute only once, maybe a few times. So the cost is dominated by the expensive first time, the code you use matters very little. Go ahead and profile it. Just make sure you don’t treat that expensive first time as “experimental error”.