Note that there are some explanatory texts on larger screens.

plurals
  1. POCan a base-class method return this, even in a derived class?
    primarykey
    data
    text
    <p>I'd like to be able to have a method in a C# base class, callable on objects of several derived classes, that returns the object itself, and have the CLR know what type the object really is - <em>i.e.</em>, the appropriate derived type. <strong>Can someone suggest a way to do it?</strong> Other, of course, than return type covariance, which C# doesn't have.</p> <p>Something like this, except that <code>Method()</code>'s return type should be the type of the derived class, not the base:</p> <pre><code>public abstract class Base { public Base Method() { return this; } } public class Derived1: Base { ... } public class Derived2: Base { ... } public class Main { public static int Main() { Derived1 d1 = new Derived1(); Derived1 x = d1.Method(); Derived2 d2 = new Derived2(); Derived2 y = d2.Method(); } } </code></pre> <p>I can only think of two ways to make this work, and I don't like either of them:</p> <ol> <li><p>Cast the result of Method() to the expected type (<em>e.g.</em>, <code>Derived1 x = (Derived) d1.Method();</code>). But casts are the tool of the Devil, and besides, the intent of the method is to return a <code>Derived1</code> or <code>Derived2</code> or ..., not a <code>Base</code>.</p></li> <li><p>Declare <code>Method()</code> as abstract in the base and implement it separately in each derived class. But that runs exactly counter to the idea of factoring out common methods. The <code>Method()</code> would be identical in each case except for its return type.</p></li> </ol>
    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