26
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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Alan
  • 45,915
  • 17
  • 113
  • 134
  • 2
    works fine here... is something else going on? – womp Jun 12 '09 at 17:41
  • seems like you're not posting enough contextual code? – Firoso Jun 12 '09 at 17:42
  • Yeah. The Debugger says the underlying type is string, but I suspect there is something else going on. – Alan Jun 12 '09 at 17:45
  • possible duplicate of [Get property value from string using reflection in C#](http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp) – nawfal Apr 27 '13 at 15:31

9 Answers9

53

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)*/});
}
Alan
  • 45,915
  • 17
  • 113
  • 134
Jake
  • 3,427
  • 2
  • 28
  • 23
  • 1
    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 Feb 01 '10 at 16:01
  • 1
    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.aspx Thanks Jb Evain. – Jake Feb 03 '10 at 07:09
  • If I only have a string with full class name, and property name like MyNameSpace1.X.Y.Z.ClassName, and PropertyName ? – Kiquenet Jan 16 '14 at 14:37
5

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");
em70
  • 6,088
  • 6
  • 48
  • 80
4
Foo f = new Foo();
f.Bar = "x";

string value = (string)f.GetType().GetProperty("Bar").GetValue(f, null);
Handcraftsman
  • 6,863
  • 2
  • 40
  • 33
4
var val = f.GetType().GetProperty("Bar").GetValue(f, null);
JP Alioto
  • 44,864
  • 6
  • 88
  • 112
3
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
  • 27,069
  • 12
  • 75
  • 95
2

Its easy to get property value of any object by use Extension method like:

public static class Helper
    {
        public static object GetPropertyValue(this object T, string PropName)
        {
            return T.GetType().GetProperty(PropName) == null ? null : T.GetType().GetProperty(PropName).GetValue(T, null);
        }
    }

Usage is:

Foo f = new Foo();
f.Bar = "x";
var balbal = f.GetPropertyValue("Bar");
Ali
  • 3,373
  • 5
  • 42
  • 54
  • Thanks to Elvis this can be amended to: `return T.GetType().GetProperty(PropName)?.GetValue(T, null);`. https://blogs.msdn.microsoft.com/jerrynixon/2014/02/26/at-last-c-is-getting-sometimes-called-the-safe-navigation-operator/ – JohnLBevan Mar 08 '18 at 17:56
2
PropertyInfo propInfo = f.GetType().GetProperty("Bar");
object[] obRetVal = new Object[0];
string bar = propInfo.GetValue(f,obRetVal) as string;
Stan R.
  • 15,757
  • 4
  • 50
  • 58
1

the getvalue with object and null worked great for me. Thanks for the posts.

Context: Looping through all properties in an MVC model for New Hires and determining their form posted values:

newHire => the Model, with many properties, whose posted form values I want to write individually to a set of database records

foreach(var propertyValue in newHire.GetProperties())
{
string propName = propertyValue.Name;

string postedValue = newHire.GetType().GetProperty(propName).GetValue(newHire, null).ToString();

}
0

To get the property names of the object by just passing the object you can use this function may this works.

just make object object a class and pass into it.

 public void getObjectNamesAndValue(object obj)
    {
        Type type = obj.GetType();
        BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
        PropertyInfo[] prop = type.GetProperties(flags);
        foreach (var pro in prop)
        {
            System.Windows.Forms.MessageBox.Show("Name :" + pro.Name + " Value : "+  pro.GetValue(obj, null).ToString());
        }

    }

But this will only work when the object properties are "Public"

Sayed Muhammad Idrees
  • 1,245
  • 15
  • 25