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
}
CrashCodes
  • 3,237
  • 12
  • 38
  • 42

4 Answers4

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

mklement0
  • 382,024
  • 64
  • 607
  • 775
Steven Behnke
  • 3,336
  • 3
  • 26
  • 34
14

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

propertyInfo.GetAccessors(nonPublic: true)[0].IsStatic;
relatively_random
  • 4,505
  • 1
  • 26
  • 48
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()
furier
  • 1,934
  • 1
  • 21
  • 39
8

Why not use

type.GetProperties(BindingFlags.Static)
dove
  • 20,469
  • 14
  • 82
  • 108
ctacke
  • 66,480
  • 18
  • 94
  • 155
  • Nice! However, in my case I want the non-static which doesn't seem to have a binding flag. – CrashCodes Dec 24 '08 at 20:40
  • This will not give you the static binding flag of the getter – Alfredo A. May 31 '18 at 15:51
  • 3
    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. – Grx70 Jan 17 '21 at 12:08