Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between MemberInfo FieldInfo

Tags:

c#

.net

vb.net

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?

like image 295
adrianwadey Avatar asked Mar 10 '16 09:03

adrianwadey


2 Answers

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.

like image 161
MakePeaceGreatAgain Avatar answered Oct 06 '22 00:10

MakePeaceGreatAgain


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.

like image 27
Michał Komorowski Avatar answered Oct 06 '22 00:10

Michał Komorowski