C#C
C#3y ago
Hugh

✅ Ensure that subclasses all have to override a specific method?

Is it possible to define a method in a class to say that it must be defined in every subclass?

For example, if I have:

public class A
{
  public virtual void DoSomething() {}
}

public class B : A
{
  public override void DoSomething()
  {
    base.DoSomething();
  }
}

public class C : A
{
}


I don't want C to be valid. I can't make DoSomething() in A abstract, as I want to be able to instantiate A.

If this isn't possible in the language, then my approach will be to change A to an abstract base class Base with an abstract DoSomething(), and a DoSomethingInternal(), and then inherit A from Base and implement DoSomething() there
Was this page helpful?