C# clone() with compiler enforced subtype recognition

26 Views Asked by At

I don't think this is possible but maybe I'm wrong. I want to have a clone() in a supertype

public abstract class LivingThing {
    public abstract T clone<T>() where T : LDBASTobj;
}

but have the implementing subtypes return its own subtype, and have the compiler enforce this.    Something like this

// doesn’t compile
public class Animal : LivingThing  {
    public Animal clone() => new Animal();
}

This seems reasonable in principle because Animal is a substituteable (covariant?) subtype of LivingThing. The subtype code above is garbage, but I hope you can see what I mean. Is this possible?

(this question C# clone from supertype isn’t what I’m after).

Thanks

0

There are 0 best solutions below