2

Given the following example

class BaseProperty
{
    
}

class DerivedProperty : BaseProperty
{
    
}

abstract class BaseWithAbstractProperty
{
    public abstract BaseProperty Property { get;  }
    public virtual BaseProperty OtherProperty { get; }
}

sealed class DerivedWithCovariantOverride : BaseWithAbstractProperty
{
    public override DerivedProperty Property { get;  }
    
    public override BaseProperty OtherProperty { get;  }
}

How do I determine that property Property of class DerivedWithCovariantOverride is an override of the abstract property with the same name on class BaseWithAbstractProperty? With OtherProperty, the following will return true

var otherProperty = typeof(BaseWithAbstractProperty).GetProperty("OtherProperty", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
var derivedProperty = typeof(DerivedWithCovariantOverride).GetProperty("OtherProperty", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

Console.WriteLine(derivedProperty.GetMethod.GetBaseDefinition() == otherProperty.GetMethod);

But with the covariant override, the following will return false

var baseProperty = typeof(BaseWithAbstractProperty).GetProperty("Property", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
var covariantProperty = typeof(DerivedWithCovariantOverride).GetProperty("Property", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

Console.WriteLine(covariantProperty.GetMethod.GetBaseDefinition() == baseProperty.GetMethod);

The only special thing I see is that the GetMethod on the covariant property returns a MethodInfo which has attribute PreserveBaseOverridesAttribute. Looking at the docs and the dotnet Github repo, it's clearly related to this covariant behavior. But all in all, it almost looks like that property is not a normal override.

Dennis Doomen
  • 8,368
  • 1
  • 32
  • 44
  • Would this help? https://stackoverflow.com/questions/2932421/detect-if-a-method-was-overridden-using-reflection-c – Renat Jul 30 '21 at 13:53
  • No, because neither `GetBaseDefinition` or `DeclaredType` point back at the base. This works with normal virtual overrides, but not with covariant properties. – Dennis Doomen Jul 30 '21 at 14:35
  • 1
    `typeof(DerivedWithCovariantOverride).GetProperties()` returns 2 different properties named Property with differences in DeclaringType, PropertyType, BindingFlags etc. I'm not sure what the easiest, most correct values are to key off of are. – ScottyD0nt Jul 30 '21 at 15:33

0 Answers0