jameszhao00
jameszhao00

Reputation: 7301

C# Reflection - Base class static fields in Derived type

In C#, when I'm reflecting over a derived type, how come I don't see base classes' static fields?

I've tried both type.GetFields(BindingFlags.Static) and type.GetFields().

Upvotes: 13

Views: 4862

Answers (4)

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422006

This is how it works. static members are really non-object-oriented stuff. They are not polymorphic and they really belong to their declaring type and are unrelated to other types in the inheritance hierarchy. For instance, a static initializer for a base class is not required to run before accessing a static member in a derived class.

static members of base classes are not returned unless BindingFlags.FlattenHierarchy is specified:

type.GetFields(BindingFlags.Static 
             | BindingFlags.FlattenHierarchy
             | BindingFlags.Public)

Upvotes: 23

Noon Silk
Noon Silk

Reputation: 55082

Because they belong to the base type, and are not inherited. Move up to that type, and you'll find them.

-- Edit

Mehrdad has the correct answer, but just for completeness:

foreach(FieldInfo f in b.GetType().GetFields(
    BindingFlags.Static
    | BindingFlags.FlattenHierarchy
    | BindingFlags.Instance
    | BindingFlags.Public
    )){
    Console.WriteLine("found: " + f.Name);
}

Upvotes: 6

choudeshell
choudeshell

Reputation: 514

Set the BindingFlags.FlattenHierarchy enumeration to Static and this will also search static members. More information: http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx

Upvotes: 5

womp
womp

Reputation: 116977

Your type is just your type - it doesn't include base types. You'll need to use BindingFlags.FlattenHierarchy if you want to search fields in base classes.

You should probably take a look at the BindingFlags documentation to accomplish what you need.

Upvotes: 3

Related Questions