Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the value of a string property via Reflection?

Tags:

public class Foo {    public string Bar {get; set;} } 

How do I get the value of Bar, a string property, via reflection? The following code will throw an exception if the PropertyInfo type is a System.String

Foo f = new Foo(); f.Bar = "Jon Skeet is god.";  foreach(var property in f.GetType().GetProperties()) {  object o = property.GetValue(f,null); //throws exception TargetParameterCountException for String type } 

It seems that my problem is that the property is an indexer type, with a System.String.

Also, how do I tell if the property is an indexer?

like image 468
Alan Avatar asked Jun 12 '09 17:06

Alan


People also ask

How does reflection set the value of a property?

To set property values via Reflection, you must use the Type. GetProperty() method, then invoke the PropertyInfo. SetValue() method. The default overload that we used accepts the object in which to set the property value, the value itself, and an object array, which in our example is null.

What does GetValue return c#?

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

What is the relation between attributes and reflection?

AttributeUsage attribute defines the program entities to which the attribute can be applied. We can use reflection to discover information about a program entity at runtime and to create an instance of a type at runtime. Most of the classes and interfaces needed for reflection are defined in the System.

How do you set property value?

To set the value of an indexed property, call the SetValue(Object, Object, Object[]) overload. If the property type of this PropertyInfo object is a value type and value is null , the property will be set to the default value for that type.


2 Answers

You can just get the property by name:

Foo f = new Foo(); f.Bar = "Jon Skeet is god.";  var barProperty = f.GetType().GetProperty("Bar"); string s = barProperty.GetValue(f,null) as string; 

Regarding the follow up question: Indexers will always be named Item and have arguments on the getter. So

Foo f = new Foo(); f.Bar = "Jon Skeet is god.";  var barProperty = f.GetType().GetProperty("Item"); if (barProperty.GetGetMethod().GetParameters().Length>0) {     object value = barProperty.GetValue(f,new []{1/* indexer value(s)*/}); } 
like image 140
Jake Avatar answered Oct 05 '22 22:10

Jake


I couldn't reproduce the issue. Are you sure you're not trying to do this on some object with indexer properties? In that case the error you're experiencing would be thrown while processing the Item property. Also, you could do this:

 public static T GetPropertyValue<T>(object o, string propertyName) {       return (T)o.GetType().GetProperty(propertyName).GetValue(o, null); }  ...somewhere else in your code... GetPropertyValue<string>(f, "Bar"); 
like image 31
em70 Avatar answered Oct 06 '22 00:10

em70