0

I've run into an issue in the past where I want two methods in an abstract class that, once implemented, would wind up with the same method definition. Obviously, I can name the methods slightly differently, but this seems inelegant because they serve the same purpose. Is there a better way to handle this than renaming?

public class foo
{
   public string spam { get; set;}
}

public abstract class absService<T> where T : foo
{
   protected void Validate(foo obj)
   {
      if (obj == null) throw new Exception("null obj");
   }
   protected abstract void Validate(T obj);

   public object DoTheThing(T obj)
   {
      Validate((foo)obj);
      Validate(obj);

      //do stuff here
   }
}

public class fooService : absService<foo>
{
   protected override void Validate(foo Obj)
   {
      if (Obj.spam == null) throw new Exception("No spam");
   }
}
R Stevens
  • 65
  • 6

1 Answers1

1

You can use virtual methods for this.

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

The nice part is that you can decide whether the code in the base class should still run or not, by calling base.Validate() if you wish. If you don't override it -for instance in another service that doesn't do more validation-, the base version will run.

public class foo
{
    public string spam { get; set;}
}

public abstract class absService<T> where T : foo
{
    // Default implementation
    protected virtual void Validate(T obj) {
        if (obj == null) throw new Exception("null obj");
    }

    public object DoTheThing(T obj)
    {
        Validate(obj); // Will call fooService.Validate() if overridden
        //do stuff here
    }
}

public class fooService : absService<foo>
{
    protected override void Validate(foo Obj)
    {
        base.Validate(Obj); // Optional, to "extend" the base method.
        if (Obj.spam == null) throw new Exception("No spam");
    }
}
mtone
  • 1,685
  • 15
  • 29