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?
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.
GetValue(Object) Returns the property value of a specified object.
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.
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.
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)*/}); }
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With