39

I have the following code:

FieldInfo[] fieldInfos;
fieldInfos = GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

What I am trying to do is get the value of one of my properties of the current instantiated instance at runtime using reflection. How can I do this?

payo
  • 4,501
  • 1
  • 24
  • 32
Icemanind
  • 47,519
  • 50
  • 171
  • 296
  • 1
    If you want a property, don't look at the fields. http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx – Jacob Krall Apr 26 '12 at 17:02
  • 3
    possible duplicate of [Get property value from string using reflection in C#](http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp) – Jacob Krall Apr 26 '12 at 17:04
  • @JacobKrall -- its an auto property actually, which I believe the compiler creates a backing field to implement the property. – Icemanind Apr 26 '12 at 17:14
  • Possible duplicate of [Get property value from string using reflection in C#](https://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp) – Michael Freidgeim Dec 06 '17 at 05:30

2 Answers2

91

Something like this should work:

var value = (string)GetType().GetProperty("SomeProperty").GetValue(this, null);
James Johnson
  • 45,496
  • 8
  • 73
  • 110
22

Try the GetProperties method, it should get you the property, instead of fields.

To retrieve the value, do something like this:

object foo = ...;
object propertyValue = foo.GetType().GetProperty("PropertyName").GetValue(foo, null);

This is using GetProperty, which returns just one PropertyInfo object, rather than an array of them. We then call GetValue, which takes a parameter of the object to retrieve the value from (the PropertyInfo is specific to the type, not the instance). The second parameter to GetValue is an array of indexers, for index properties, and I'm assuming the property you're interested in isn't an indexed property. (An indexed property is what lets you do list[14] to retrieve the 14th element of a list.)

David Yaw
  • 27,383
  • 4
  • 60
  • 93