Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetFields of derived type

Tags:

c#

reflection

I am trying to reflect the fields in a derived type but it's returning the fields of the base type.

public class basetype
{
    string basevar;
}

public class derivedtype : basetype
{
    string derivedvar;
}

In some function:

derivedtype derived = new derivedtype();

FieldInfo[] fields = derived.GetType().GetFields();

This will return basevar, but not derivedvar. I've tried all the different bindings and it doesn't seem to make a difference.

Also, I'm doing this in ASP.NET within App_Code where basevar is defined in App_Code and derivedvar is a user control defined in App_Controls where the types are not in scope.

like image 513
KenEucker Avatar asked Oct 08 '10 02:10

KenEucker


1 Answers

As is, this will return nothing as the default binding is for public fields only.

As is also, derivedtype isn't derived from basetype

With:

FieldInfo[] fields = derived.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

It returns derivedvar. I've just checked in LINQPad.

If I change derivedtype to be derived from basetype, then I can get both fields with:

FieldInfo[] fields = derived.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Concat(derived.GetType().BaseType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)).ToArray();
like image 140
Jon Hanna Avatar answered Sep 23 '22 02:09

Jon Hanna