Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memberInfo.GetValue() C#

Tags:

c#

reflection

How to get an instance's member's values?

With propertyInfos there is a propertyInfo.GetValue(instance, index), but no such thing exists in memberInfo.

I searched the net, but it seems to stop at getting the member's name and type.

like image 375
Boris Callens Avatar asked Sep 22 '08 15:09

Boris Callens


2 Answers

You have to downcast to FieldInfo or PropertyInfo:

switch (memberInfo)
{
  case FieldInfo fieldInfo:
    return fieldInfo.GetValue(obj);
  case PropertyInfo propertyInfo:
    return propertyInfo.GetValue(obj);
  default:
    throw new InvalidOperationException();
}
like image 150
Carlo V. Dango Avatar answered Sep 20 '22 12:09

Carlo V. Dango


I think what you need is FieldInfo.

like image 31
Matt Howells Avatar answered Sep 20 '22 12:09

Matt Howells