Strange Effect with Overridden Properties and Reflection

Posted by naacal on Stack Overflow See other posts from Stack Overflow or by naacal
Published on 2011-11-15T17:13:10Z Indexed on 2011/11/15 17:50 UTC
Read the original article Hit count: 209

Filed under:
|
|
|

I've come across a strange behaviour in .NET/Reflection and cannot find any solution/explanation for this:

Class A 
{
   public string TestString { get; set; }
}

Class B : A
{
   public override string TestString
   {
      get { return "x"; }
   }
}

Since properties are just pairs of functions (get_PropName(), set_PropName()) overriding only the "get" part should leave the "set" part as it is in the base class. And this is just what happens if you try to instanciate class B and assign a value to TestString, it uses the implementation of class A.

But what happens if I look at the instantiated object of class B in reflection is this:

PropertyInfo propInfo = b.GetType().GetProperty("TestString");
propInfo.CanRead  ---> true
propInfo.CanWrite ---> false(!)

And if I try to invoke the setter from reflection with:

propInfo.SetValue("test", b, null);

I'll even get an ArgumentException with the following message:

Property set method not found.

Is this as expected? Because I don't seem to find a combination of BindingFlags for the GetProperty() method that returns me the property with a working get/set pair from reflection.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET