Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy restricting return type for method and property inheritance so that descendants are not allowed?
    primarykey
    data
    text
    <p>Given the following hypothetical situation:</p> <pre><code>class ClassParent { } interface IClassProvider { ClassParent Get(); } </code></pre> <p>Why is this then illegal IClassProvider implementation:</p> <pre><code>class ClassChild : ClassParent, IClassProvider { ClassChild Get() { return this; } } </code></pre> <p>It also doesn't work for inheriting properties and implementing base class instead of an interface like in the example.</p> <p>ClassChild <em>is</em> ClassParent. Why does it not compile then? The compiler is clearly aware of a compile-time type of a class, that's why the following works:</p> <pre><code>void DoSomething(object o) { ... }; void DoSomething(ConcreteClass c) { ... }; DoSomething(new ConcreteClass()); //Calls the second overload of the method because of static type resolving </code></pre> <p>In layered scenarios this forces me to have a bunch of proxy-methods and needlessly clutter my code when the underlying situation is clear. Frankly I can't think of any problems or ambiguities if that was supported. I would be happy with compile-time (static) resolution, like it works with overloads in the second example.</p> <p>Edit: I know that the compiler expects the following:</p> <pre><code>class ClassChild : ClassParent, IClassProvider { ClassParent Get() { return this; } } </code></pre> <p>and I know that it would work, I'm asking for an explanation why is it not supported or a scenario in which it would cause either a) problems or b)ambiguities worse than with overloads, which are supported.</p> <p>Edit 2: This is as it seems another duplicate of a same old question as answered by apparently MS himself in <a href="https://stackoverflow.com/questions/1319663/why-c-doesnt-allow-inheritance-of-return-type-when-implementing-an-interface">this SO question</a>. I'm marking @Euphoric 's post as answer because he provided a name for the feature which helped finding the "solution".</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload