Ok, I have a number of different classes deriving from a base class. This base class is an abstract containing commom methods.
One of the methods is a Copy
method, wich should be present in all derived classes, so, I've put it in the base class.
BUT, I want it to return the derived type
not the base nor object.
The solution I got for that, is using a type paramter:
abstract class CopyableClass<T>
{
public abstract T Copy();
}
class DerivedClass : CopyableClass<DerivedClass>
{
public override DerivedClass Copy()
{
//do what is needed for copy and return a new DerivedClass
}
}
So, the main purpose here is to
Remove the type parameter in the base class and still make the method return the corresponding derived type.
One workaround.
The best thing I could do so far is one of the comments below, but it still uses a generic parameter
abstract class BaseClass
{
//base methods not related to deriving type
}
interface ICopyable<T>
{
T Copy();
}
class DerivedClass : BaseClass, ICopyable<DerivedClass>
{
public DerivedClass Copy()
{
//do what is needed for copy and return a new DerivedClass
}
}
abstract class CopyableClass<T>:where T:CopyableClass{}
– Taction