My base class has a public static method, but when I call typeof(TDerived).GetMethods(BindingFlags.Public |BindingFlags.Static
) my method doesn't get returned. (TDerived of course inherits in some way from my base class). I don't have a reference to my base class at the place of this query.
What am I doing wrong?
Asked
Active
Viewed 5,664 times
16

TDaver
- 7,164
- 5
- 47
- 94
-
You can get hold of the base class of your own class through reflection though, use `typeof(TDerived).BaseType` – Lasse V. Karlsen Apr 15 '11 at 09:59
-
possible duplicate of [C# Reflection - Base class static fields in Derived type](http://stackoverflow.com/questions/1325280/c-sharp-reflection-base-class-static-fields-in-derived-type) – nawfal Jun 03 '13 at 16:54
2 Answers
33
Use the BindingFlags.FlattenHierarchy
flag:
typeof(TDerived).GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)
It is a documented behavior in the Remarks section for Type.GetMethods(BindingFlags)
method.

Ondrej Tucny
- 27,626
- 6
- 70
- 90
2
If you want to get hold of all the static members of your direct base type, ie. only the static methods of the class from which the current class inherits, then you can access it through reflection as well.
Your code, from your question, would then become:
typeof(TDerived).BaseType.GetMethods(BindingFlags.Public | BindingFlags.Static)
^---+---^
|
+-- add this
Of course, this would only get the static methods of that type. If you want all the static methods of your own type and the base type(s), then go with the FlattenHierarchy option that @Ondrej answered with, much better.

Community
- 1
- 1

Lasse V. Karlsen
- 380,855
- 102
- 628
- 825