In C#, if you use Type.GetFields() with a type representing a derived class, it will return a) all explicitly declared fields in the derived class, b) all backing fields of automatic properties in the derived class and c) all explicitly declared fields in the base class.
Why are the d) backing fields of automatic properties in the base class missing?
Example:
public class Base {
public int Foo { get; set; }
}
public class Derived : Base {
public int Bar { get; set; }
}
class Program {
static void Main(string[] args) {
FieldInfo[] fieldInfos = typeof(Derived).GetFields(
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.FlattenHierarchy
);
foreach(FieldInfo fieldInfo in fieldInfos) {
Console.WriteLine(fieldInfo.Name);
}
}
}
This will show only the backing field of Bar, not Foo.
A field being a backing field has no influence on reflection. The only relevant property of backing fields is that they are private.
Reflection functions don’t return private members of base classes, even if you use
FlattenHierarchy. You will need to loop manually over your class hierarchy and ask for private fields on each one.I think
FlattenHierarchyis written with the intent to show all members visible to code in the class you look at. So base members can be hidden/shadowed by members with the same name in a more derived class and private members are not visible at all.