HCP
HCP

Reputation: 1042

How to i return the value of a property if i dont know the propertyname at run-time?

And let's assume for simplicity that the value of the property needs to always be returned as a string.

public string GetTheValueOfTheProperty(PropertyInfo propertyInfo,Object myObject){
       string propname = propertyInfo.Name;
       if (propName == "IsSelected"){
          return myObject.IsSelected.ToString();
       }
    //...
}

This works, but it doesn't work if I don't know the name of the property. How would I do that in that scenario ?

Upvotes: 0

Views: 181

Answers (2)

Paolo Tedesco
Paolo Tedesco

Reputation: 57302

The PropertyInfo object lets you invoke the property on the object:

object value = propertyInfo.GetGetMethod().Invoke(myObject, new object[] { });

Upvotes: 0

Kieren Johnstone
Kieren Johnstone

Reputation: 42013

http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getvalue.aspx

You can call propertyInfo.GetValue(myObject, null);.

You can convert to a string with ToString(), but you should check for null values first - otherwise you'll get a NullReferenceException.

Upvotes: 5

Related Questions