Casey Crookston Casey Crookston - 3 months ago 19
C# Question

Return value of property from object and property name

Given an object and the name of a property, I'm trying to use reflection to get the value of that property. I've seen several threads here that are getting me close, but I'm not nailing it just yet. I happen to know that the value will be of type string.

public string GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(????);
}

Answer

Just pass the src object like this:

public string GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null).ToString();
}