In C# overriding auto-property and providing only one accessor makes reflection via PropertyInfo
"lose" the other one, even though it is defined in base class.
It can look strange at a first glance, but seems to be reasonable after more detailed analysis.
However, changing override
to sealed override
also changes this behavior and allows to get all accessors:
using System.Reflection;
using NUnit.Framework;
[TestFixture]
public class PropertySealedOverrideReflectionTests
{
public class Base
{
public virtual object Override { get; set; }
public virtual object SealedOverride { get; set; }
}
public class Derived : Base
{
public override object Override { set => base.Override = value; }
public sealed override object SealedOverride { set => base.Override = value; }
}
[Test]
public void Override()
{
PropertyInfo overrideProperty = typeof(Derived).GetProperty(nameof(Derived.Override));
// ---
// getter from base class is "invisible" here
// ---
Assert.False(overrideProperty.CanRead);
Assert.Null(overrideProperty.GetMethod);
}
[Test]
public void SealedOverride()
{
PropertyInfo sealedOverrideProperty = typeof(Derived).GetProperty(nameof(Derived.SealedOverride));
// ---
// after changing to "sealed override" getter is in place
// ---
Assert.True(sealedOverrideProperty.CanRead);
Assert.NotNull(sealedOverrideProperty.GetMethod);
}
}
What does compiler change in type to do sealed override
in provided scenario? What is the reason of such behavior?
Override
in base class,sealed override Override
in child class? Allsealed
should do in this instance is prevent you from overriding in another child class, like a child of Derived wouldn't be able to override SealedOverride – Normalizeget
and theset
accessor. Then to achieve that, it has to actually override theget
accessor even though you do not write any getter in your override. Of course the C# compiler will just call the base implementation in the accessor it "invents" itself. With reflection, the presence of that get accessor shows up. – Anussealed override
should do, the problem and behavior I refer to is accessibility of the property getter from base class via reflection, please see unit tests from the question. – Broadnax