hmqcnoesy
hmqcnoesy

Reputation: 4225

GetField const in type's base class

How can I use reflection in .NET 4 to get field info for a base class from a derived class?

For instance,

class Parent
{
    public const bool ParentField = true;
}

class Child : Parent
{
    public const bool ChildField = true;
}

Using those classes:

Console.WriteLine(p.GetType().GetField("ParentField"));
Console.WriteLine(c.GetType().GetField("ChildField"));
Console.WriteLine(c.GetType().GetField("ParentField"));

The third line doesn't work the way I expect. GetField returns null when getting a field from the base type. I have tried the overload of GetField with all the different BindingsFlags values I can think of, but it always returns null.

EDIT

I should have been clear that this

c.GetType().GetField("ParentField",BindingFlags.FlattenHierarchy)

also returns null.

Upvotes: 0

Views: 468

Answers (1)

dee-see
dee-see

Reputation: 24078

To get the inherited constants you have to be a little more specific with your binding flags:

c.GetType().GetField("ParentField", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)

Upvotes: 3

Related Questions