How can I get the value of a string property via Reflection?
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");
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)*/});
}
Foo f = new Foo();
f.Bar = "x";
string value = (string)f.GetType().GetProperty("Bar").GetValue(f, null);