How do I get the value of a MemberInfo
object? .Name
returns the name of the variable, but I need the value.
I think you can do this with
Although I generally agree with Marc's point about not reflecting fields, there are times when it is needed. If you want to reflect a member and you don't care whether it is a field or a property, you can use this extension method to get the value (if you want the type instead of the value, see nawful's answer to this question):
public static object GetValue(this MemberInfo memberInfo, object forObject)
{
switch (memberInfo.MemberType)
{
case MemberTypes.Field:
return ((FieldInfo)memberInfo).GetValue(forObject);
case MemberTypes.Property:
return ((PropertyInfo)memberInfo).GetValue(forObject);
default:
throw new NotImplementedException();
}
}