I have a nongeneric interface to a generic class group. I have a method which uses covariance to return a strongly typed instance in a class derived from an abstract implementation of the non-generic class group.
So basically with this setup, I have a number of classes, e.g. ActualThing1 and ActualThing2. These classes have a Clone method which returns a strongly-typed clone of themselves.
Below is how I’ve structured the interface & classes. I am not sure this is right.
Normally, I wouldn’t have the non-generic abstract class at all. But this is necessary because there is a situation where I have to do something to child objects, referencing an internal method _SomethingNeededInternally. This can’t be done using the interface, since it’s protected, nor can it be done from inside the generic class, since the children might not be the same type (they might be a different type derived from the interface). Hence the non-generic base class Something.
This works, but what doesn’t quite make sense to me is the explicit implementation of ISomething.Clone that is needed in my abstract Something class. It has to be there, but it shouldn’t be implemented, since I want that implementation deferred to the generic class that derives from it. But there’s no such syntax as abstract ISomething ISomething.Clone().
But that code (where the exception is throw) can’t ever execute, can it, since I don’t have any non-generic implementations of this object?
I guess I’m wondering if there is a better way to do this, because it seems not right. That is, I am depending on the fact that a non-generic class is never created from the interface, which smells funny.
public interface ISomething
{
// ...
ISomething Clone();
}
public abstract class Something: ISomething
{
ISomething ISomething.Clone()
{
throw new Exception("This should not be happening");
}
protected int _SomethingNeededInternally;
}
public abstract class Something<T>: Something, ISomething where T: ISomething, new()
{
public abstract T Clone();
ISomething ISomething.Clone()
{
return Clone();
}
}
public interface IActualThing {} // this could be any interface
public class ActualThing: Something<ActualThing>, IActualThing
{
public override ActualThing Clone()
{
return new ActualThing(); // do cloning here
}
}
Would adding required method as implementation of Clone work for you?
(I’m still not exactly sure what your whole problem is, this will just solve syntax for abstract explicit interface implementation.)