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?

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to programatically check if the property is static?
@gjdanis You need to check if the GetSetMethod or GetGetMethod methods on PropertyInfo, the MethodInfo will tell you if it is start.
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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.