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 thr
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"
Foo f = new Foo();
f.Bar = "x";
string value = (string)f.GetType().GetProperty("Bar").GetValue(f, null);
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");
var val = f.GetType().GetProperty("Bar").GetValue(f, null);
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");
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;
}
}