adrianwadey
adrianwadey

Reputation: 1759

What's the difference between MemberInfo FieldInfo

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?

Upvotes: 7

Views: 4596

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

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.

Upvotes: 7

Michał Komorowski
Michał Komorowski

Reputation: 6238

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.

Upvotes: 4

Related Questions