Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property hiding and reflection (C#)

Tags:

Declaring a property in a derived class that matches the name of a property in the base class "hides" it (unless it overrides it with the override keyword). Both the base and derived class properties will be returned by Type.GetProperties() if their types don't match. However, if their types do match, shockingly only the derived class's property is returned. For instance:

class A {     protected double p;     public int P { get { return (int)p; } set { p = value; } } } class B : A {     public new int P { get { return (int)p; } set { p = value; } } } class C : B {     public new float P { get { return (float)p; } set { p = value; } } } 

Calling typeof(C).GetProperties() will only return B.P and C.P. Is it possible to call GetProperties() in a way that returns all three? There is almost certainly a way to do it by traversing the inheritance hierarchy, but is there a cleaner solution?

like image 787
Eric Mickelsen Avatar asked Apr 26 '10 16:04

Eric Mickelsen


1 Answers

GetProperties is defined as all public properties of the type.

You could get their get and set methods using:

typeof(C).GetMethods()          .Where(m => m.Name.StartsWith("set_") || m.Name.StartsWith("get_")) 

Although this seems like a bad idea, compared to going down the inheritance hierarchy to get the properties.

like image 138
Yuriy Faktorovich Avatar answered Sep 21 '22 13:09

Yuriy Faktorovich