I am writing an extension to get Description and other attributes from an Enum
.
I have seen examples using FieldInfo
and others using MemberInfo
. Can someone explain what the difference is and when it would make a difference which one I should use?
MemberInfo
is the abstract base-class for both FieldInfo
and PropertyInfo
. So when you want to access a field use FieldInfo
, for properties take PropertyInfo
.
EDIT: To get attributes set on your enum-values you may use this:
var attr = typeof(MyEnum).GetField(myEnumValue.ToString()).GetCustomAttributes(typeof(Description), false);
if (attr.Length > 0) return attr[0].Description;
In this case you could also use GetMember
instead of GetField
as GetCustomAttributes
is defined on MemberInfo
and therefor provided on both FieldInfo
and PropertyInfo
.
FieldInfo class is derived from MemberInfo class and it has additional methods/properties that are specific only for fields. MemberInfo class is more general, it can describe constructors, properties, methods, events and not only fields.
I assume that some people use FieldInfo and some MemberInfo depending on requirements. In some cases information provided by MemberInfo are enough and in some not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With