Reputation: 11484
I have this code,
public abstract class BaseClass
{
public object CommonMethod<T>()
{
//Common code
CustomMethod(); //Call child method
return (T)CustomObject;
}
internal abstract void CustomMethod();
}
public class ChildClass : BaseClass
{
public MyDTO CommonMethod()
{
return (MyDTO)base.CommonMethod<MyDTO>(); //Call Base class common code
}
internal override void CustomMethod()
{
//Custom Code, specific to child class
}
}
I have some common code which I have placed in the base class (BaseClass.CommonMethod), But finally same method should run child class specific code (ChildClass.CustomMethod).
Is this implementation correct or is there any other preferred/better implementation to achieve this?
Final code (Updated according to the answers) :
public abstract class BaseClass<T> where T : IDTO
{
public T CommonMethod()
{
//Common code
CustomMethod(); //Call child method
return (T)CustomObject;
}
internal abstract void CustomMethod();
}
public class ChildClass : BaseClass<MyDTO>
{
internal override void CustomMethod()
{
//Custom Code, specific to child class
}
}
Upvotes: 0
Views: 110
Reputation: 1101
With small corrections your code looks good. You don't need to override CommonMethod, though, if you put return value as T:
public abstract class BaseClass<T>
{
public T CommonMethod()
{
//Common code
T result = CustomMethod(); //Call child method
return result;
}
internal abstract T CustomMethod();
}
public class ChildClass : BaseClass<MyDTO>
{
internal override MyDTO CustomMethod()
{
//Custom Code, specific to child class
}
}
In my example I assumed that you return CustomObject from CustomMethod, otherwise I'm not quite sure where are you getting this object from.
Upvotes: 1
Reputation: 28558
I don't think you need the cast (MyDTO)base.CommonMethod<MyDTO>();
as your base method is already casting the result.
You will need to make sure that CustomObject
can be cast to T
, that bit looks fishy to me.
CustomerObject
must inherit from MyDTO
, therefore T
must implement MyDTO
(I think)
Upvotes: 1