Consider this interesting set of types:
class A { public virtual int MyProperty { get; set; } }
class B : A { public override int MyProperty { get; set; } }
class C : B { public new virtual int MyProperty { get; set; } }
class D : C { public override int MyProperty { get; set; } }
class E : D { public new int MyProperty { get; set; } }
I see three different properties here, with five implementations hiding or overriding each other.
I'm trying to get the set of property declarations for type E
:
A.MyProperty
C.MyProperty
E.MyProperty
But my code below gives me the set of property implementations:
A.MyProperty
B.MyProperty
C.MyProperty
D.MyProperty
E.MyProperty
What do I need to do to get the property declarations?
Or is there any chance that B.MyProperty
will ever return a value other than A.MyProperty
for any instance of E
?
If my approach is heading in the wrong direction: How do I get all property members of a type including any hidden ones, but not including those that will never have different values?
void GetProperties(Type type)
{
if (type.BaseType != null)
{
GetProperties(type.BaseType);
}
foreach (var item in type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public))
{
Console.WriteLine("{0}.{1}", type.Name, item.Name);
}
}
Desired outputs:
typeof(A) typeof(B) typeof(C) typeof(D) typeof(E) ------------ ------------ ------------ ------------ ------------ A.MyProperty A.MyProperty A.MyProperty A.MyProperty A.MyProperty C.MyProperty C.MyProperty C.MyProperty E.MyProperty