I experienced an interesting gotcha with reflection today. I had a base class with a virtual property:
class BaseClass
{
private string _someProperty = "Hello!";
public virtual string SomeProperty
{
get { return _someProperty; }
set { _someProperty = value; }
}
}
In a subclass I overrode the property, but only implemented the setter:
class SubClass : BaseClass
{
public override string SomeProperty
{
set { base.SomeProperty = value + " and stuff"; }
}
}
You can get/set the property of an instance of SubClass normally. However, if you try to get the property's value with reflection, it's not quite straightforward. Something like this, won't work:
SubClass sub = new SubClass();
Type t = sub.GetType();
PropertyInfo prop = t.GetProperty("SomeProperty");
string s = prop.GetValue(sub, null).ToString();
The call to GetValue() fails because the getter doesn't exist on the SubClass. It sounds obvious in retrospect, but it sure threw me for a loop today. See the attachment for a working example.