Overriding base methods in C#

When you have a base method which can be overridden by a child class, it’s important to keep in mind that you are completely overriding the base method. So, you need to ensure that the child class method does everything that is required. In other words, the child class method may still need to do what the base class method was doing.

For an example, let’s say you have the following base class

public abstract class BaseServiceProcess
{
   public virtual void PreProcessStep(object args)
   {
      processEngine = new ProcessEngine();
      processEngine.StartDate = DateTime.Now;
   }
}

And then you have the following child class

public class ChildProcess : BaseServiceProcess
{
   public override void PreProcessSteps(object args)
   {
      processEngine.Detail = "Started from Child.";
   }
}

In this situation, the code would break because processEngine is not initialised, because that piece of code is not called.

So, you could resolve the issue by changing the child class.

public class ChildProcess : BaseServiceProcess
{
   public override void PreProcessSteps(object args)
   {
      processEngine = new ProcessEngine();
      processEngine.StartDate = DateTime.Now;
      processEngine.Detail = "Started from Child.";
   }
}

You could also call the base class method from the child class, as demonstrated below.

public class ChildProcess : BaseServiceProcess
{
   public override void PreProcessSteps(object args)
   {
      base.PreProcessSteps(args);
      processEngine.Detail = "Started from Child.";
   }
}

I hope that helps!

Subscribe

0 comments