Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

abstract method in a virtual class

I have a c# Class that has lots of virtual methods, some of these methods are essentially abstract ( they are fully implemented in subclasses and the base class is empty).

To get it to compile i am throwing an InvalidOperationException in the base class with a comment on what should be done. This just feels dirty.

Is there a better way to design my classes?

edit: It is for the middle tier of an application that will be ran in canada, half of the methods are generic hence the virtual. and half of the methods are province specific.

Public class PersonComponent() 
{

 public GetPersonById(Guid id) {
  //Code to get person - same for all provinces
 }

 Public virtual DeletePerson(Guid id) {
  //Common code
 }

 Public virtual UpdatePerson(Person p) {
  throw new InvalidOperation("I wanna be abstract");
 }

Public Class ABPersonComponent : PersonComponent
{
    public override DeletePerson(Guid id) 
    {
       //alberta specific delete code
    }

    public override UpdatePerson(Person p) 
    {
       //alberta specific update codecode
    }

}

hope this makes sense

like image 697
aaron Avatar asked Dec 05 '22 06:12

aaron


1 Answers

Mark the base class as abstract, as well as the methods that have no implementation.

Like so

public abstract class BaseClass
{

    public abstract void AbstractMethod();
}

public class SubClass: BaseClass
{
    public override void AbstractMethod()
    {
        //Do Something
    }
}

You can't have abstract methods outside of an abstract class. Marking a class as abstract means you won't be able to instantiate it. But then it doesn't make any sense to. What are you going to do with a class that doesn't implement the methods anyway?

Edit: From looking at your class, yeah I'd make PersonComponent abstract along with the UpdatePerson method. Either that, or if UpdatePerson just doesn't do anything for a PersonComponent keep it as is, but make the UpdatePerson method empty for PersonComponent.

like image 55
Ray Avatar answered Dec 23 '22 14:12

Ray