+2  A: 
Foo f = new Foo();
f.Bar = "Jon Skeet is god.";

foreach(var property in f.GetType().GetProperties())
{
    if(property.Name != "Bar")
    {
         continue;
    }
    object o = property.GetValue(f,null); //throws exception TargetParameterCountException for String type
}

And here is for the followup:

class Test
{
 public class Foo
 {
  Dictionary<string, int> data =new Dictionary<string,int>();
  public int this[string index]
  {
   get { return data[index]; }
   set { data[index] = value; }
  }

  public Foo()
  {
   data["a"] = 1;
   data["b"] = 2;
  }
 }

 public Test()
 {
  var foo = new Foo();
  var property = foo.GetType().GetProperty("Item");
  var value = (int)property.GetValue(foo, new object[] { "a" });
  int i = 0;
 }
}
Jake Pearson
Based on the other comments, you will need to change the null on get value to the proper indexer value(s).
Jake Pearson
+2  A: 

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");
emaster70
Yes, thats the problem.
Alan
+10  A: 

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)*/});
}
Cipher
That's inexact. Item is the default name for indexers, but anyone can use a IndererNameAttribute on the indexer property to change that. You have to look for the DefaultMemberAttribute on the type to get the actual indexer name.
Jb Evain
I was completely unaware of the IndexerName attribute! Thank you. You can find more information here: http://bartdesmet.net/blogs/bart/archive/2006/09/09/4408.aspxThanks Jb Evain.
Cipher
You can in VB..
Jouke van der Maas
+1  A: 
Foo f = new Foo();
f.Bar = "x";

string value = (string)f.GetType().GetProperty("Bar").GetValue(f, null);
Handcraftsman
+1  A: 
var val = f.GetType().GetProperty("Bar").GetValue(f, null);
JP Alioto
+1  A: 
PropertyInfo propInfo = f.GetType().GetProperty("Bar");
object[] obRetVal = new Object[0];
string bar = propInfo.GetValue(f,obRetVal) as string;
Stan R.
what exactly is the downvote for? this code works as expected.
Stan R.
No idea. Some people down vote just to down vote.
Alan