mardi 3 septembre 2019

Why does sealed override of a property in C# copy not overriden accessor from base type?

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?





Aucun commentaire:

Enregistrer un commentaire