41

FieldInfo has an IsStatic member, but PropertyInfo doesn't. I assume I'm just overlooking what I need.

Type type = someObject.GetType();

foreach (PropertyInfo pi in type.GetProperties())
{
   // umm... Not sure how to tell if this property is static
}

4 Answers 4

58

To determine whether a property is static, you must obtain the MethodInfo for the get or set accessor, by calling the GetGetMethod or the GetSetMethod method, and examine its IsStatic property.

https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo

Sign up to request clarification or add additional context in comments.

1 Comment

BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy worked for me.
15

As an actual quick and simple solution to the question asked, you can use this:

propertyInfo.GetAccessors(nonPublic: true)[0].IsStatic;

Comments

10

Better solution

public static class PropertyInfoExtensions
{
    public static bool IsStatic(this PropertyInfo source, bool nonPublic = false) 
        => source.GetAccessors(nonPublic).Any(x => x.IsStatic);
}

Usage:

property.IsStatic()

Comments

8

Why not use

type.GetProperties(BindingFlags.Static)

3 Comments

Nice! However, in my case I want the non-static which doesn't seem to have a binding flag.
This will not give you the static binding flag of the getter
This is not a valid solution. First of all, it does not even list static properties, because binding flags should also have access level specified (BindingFlags.Public, BindingFlags.NonPublic, or both). Second of all, this simply lists static properties (input is Type, output is PropertyInfo[]), whereas the question is "given a property, how to determine if it is static?" (input is PropertyInfo, output is bool). I guess the closest thing to your proposal would be to slap .Contains(property) at the end, but I'd argue it would be a sub-optimal solution.

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.