C# Reflection – How to Get the Value of a String Property via Reflection

c++propertiesreflectionstring

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?

Best Answer

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)*/});
}