Property Value

  • Thread starter Thread starter Islam Elkhayat
  • Start date Start date
I

Islam Elkhayat

I'm using System.Reflection.PropertyInfo to list all property in a class..
I can access the property name& type but i can't get the current... How
could i access the current property value??
 
PropertyInfo only gives you information about the class, not about a
particular instance. You need to call the GetValue method of the
PropertyInfo object you have, and pass it an object of the appropriate
type (the type from which you got the PropertyInfo in the first place)
from which to get the value. For example:

myClass myObject = new myClass("a particular description");
// Notice that in the next line, GetProperty gets a property from the
_type_ of myObject,
// not from myObject itself. In other words, the object pi has no idea
that it came
// from a GetType() result from myObject. You would get the same result
saying
// pi = typeof(myClass).GetProperty("Description"); which doesn't
involve myObject
// at all.
PropertyInfo pi = myObject.GetType().GetProperty("Description");

// So, in the following line you have to pass myObject, which tells
GetValue from which
// instance to fetch the property value.
string propertyValue = (string)pi.GetValue(myObject, null);
 
Back
Top