Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a property value using reflection

Tags:

c#

reflection

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?

like image 508
Icemanind Avatar asked Apr 26 '12 17:04

Icemanind


People also ask

How to get the property value using reflection in C#?

Get property valuesUse PropertyInfo. GetValue() to get a property's value. Note: Notice the difference between reflecting a type's properties vs reflecting an object's properties (typeof(movie). GetProperties() vs movie.

What does GetValue return C#?

GetValue(Object) Returns the property value of a specified object.

What is C# reflection?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.


2 Answers

Something like this should work:

var value = (string)GetType().GetProperty("SomeProperty").GetValue(this, null); 
like image 137
James Johnson Avatar answered Sep 30 '22 17:09

James Johnson


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.)

like image 27
David Yaw Avatar answered Sep 30 '22 18:09

David Yaw