1

There's a great post here that gives a way to get the value of a property by its string name:

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

Currently, I'm trying to get the value of a static property in a base class. If I try to use BaseClass.Prop as 'src', however, I get a null reference exception. While src isn't associated with an explicit instance, the value of Prop I'm trying to get nevertheless still exists.

Is there a workaround for static properties?

Community
  • 1
  • 1
rookie
  • 2,783
  • 5
  • 29
  • 43

2 Answers2

4

Don't send a src when calling static properties.

 Type t = src.GetType();

 if (t.GetProperty(propName).GetGetMethod().IsStatic)
 {   
     src = null;
 }
 return t.GetProperty(propName).GetValue(src, null);
T McKeown
  • 12,971
  • 1
  • 25
  • 32
  • Is there a way to programatically check if the property is static? – rookie Apr 14 '14 at 19:30
  • checkout this post [http://stackoverflow.com/questions/451453/how-to-get-a-static-property-with-reflection] – MethodMan Apr 14 '14 at 19:31
  • @gjdanis You need to check if the GetSetMethod or GetGetMethod methods on `PropertyInfo`, the MethodInfo will tell you if it is start. – vcsjones Apr 14 '14 at 19:32
1

To get a static property, you cannot pass an object reference. To detect if a property-get is static, look at propertyInfo.GetGetMethod().IsStatic. Here's your GetPropValue method:

public static object GetPropValue(object src, string propName)
{
    var propertyInfo = src.GetType().GetProperty(propName);
    if (propertyInfo.GetGetMethod().IsStatic)
        return propertyInfo.GetValue(null, null);
    else
        return propertyInfo.GetValue(src, null);
}
Michael Gunter
  • 12,528
  • 1
  • 24
  • 58