Basically my setting is this:
public abstract class BaseObject{
public abstract BaseObject Clone();
}
public class DerivedObject : BaseObject{
public DerivedObject Clone()
{
//Clone logic
}
}
The above code doesn’t compile because it isn’t possible to change the return type when overriding a method.
Is it possible to achieve that every derived type’s Clone method returns an argument of it’s own type (maybe through generics)?
Well, C# doesn’t allow covariant return types as you’ve found… but you can use generics:
This solution can be a pain in various ways – not least because it’s hard to understand – but it can work reasonably well in many situations.
EDIT: The reason I’ve included the constraint on T is so that
BaseObjectcan call “its own” methods on instances ofT, which is usually very handy. If you don’t need this though, you can lose the constraint.