79384455

Date: 2025-01-24 13:12:35
Score: 0.5
Natty:
Report link

As already answered by @ehiller, it's only possible to have covariant returns if a property is readonly, but you can still set its value when calling the constructor. Here's an example:

  1. Define a couple of types that are going to be used to declare the properties (using interfaces in this example):
public interface IBase {
    void Method1();
}

public interface IDerived : IBase {
    void Method2();
}
  1. Define the types that declare the properties:
public class Base {
    public virtual IBase Property { get; }

    public Base(IBase b) {
        Property = b;
    }

    public void CallMethod1() {
        Property.Method1();
    }
}

public class Derived : Base {
    // Property with covariant return. 
    public override IDerived Property { get; }

    public Derived(IDerived d) : base(d) {
        Property = d;  // No setter, but it's legal to set the value here.
    }

    public void CallMethod2() {
        Property.Method2();
    }
}
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @ehiller
  • Low reputation (0.5):
Posted by: metator