Context: this is for an engine, which is full of generic classes so that future users can extend certain parts of the behavior without concerning themselves with the inner workings of the engine itself.
Right now, I need a class C:
public class C
{
public C Copy(params) { ... }
}
But also an extension class D:
public class D : C
{
public D Copy(params) { ... }
}
Basically I have some generic classes, but I need a copy method (actually it’s a “make a copy at a new location” method, but that’s immaterial) which returns the right type.
public class SampleClass<T>
where T : C
{
public void Stuff()
{
...
T copy = favoriteThing.Copy(params);
...
}
}
and etc. I could just cast it, and trust future implementers to get it right, but I’d rather make it all explicit with contracts. Are there any elegant ways to do this?
One way might be to define an
ICopyable<T>interface that’s implemented byCandD:Now if
SampleClass<T>constrainsTtoICopyable<T>, it can callCopyand get back an object of typeTwithout any casts: