Reflection on partially overriden property?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

Here is a short code snippet:

//*************************

public class Base
{
public virtual int X
{
get { return 0; }
set { }
}
}

public class Derived : Base
{
public override int X
{
set { } // only setter overriden here!
}
}

public class Test
{
static void Main()
{
Derived d = new Derived();
d.X = 0; // set OK
int x = d.X; // get OK

PropertyInfo pi = typeof(Derived).GetProperty("X");
pi.SetValue(d, 0, null); // set OK
x = (int)pi.GetValue(d, null); // get NOT OK (exception)
}
}

//*************************

I can access the getter for the X property in "normal" way, however I can't
do it using reflection (I get an exception "Property Get method was not
found"). It seems to be caused by "asymmetric" override (only setter modified
in the Derived class). The PropertyInfo object I get only refers to the
"setting part" of the property (for example, CanRead is false). It can be
used to invoke the setter but not the getter.

How to get value of such property through reflection? Or maybe I have missed
something?

Thx,
Jakub
 
What happends if you use the method get_X instead?
Thanks! I haven't thought it can be worked-around this way... It works.

Anyway, isn't the lack of access to the getter via PropertyInfo a kind of
bug in the .NET reflection implementation? If I don't override neither the
setter or getter in Derived, than I can see both inherited setter and getter
via PropertyInfo. If I do override both, than I can see both. But if I
override one of them, the other one becomes not accessible. Looks strange to
me...
 
Back
Top