Search code examples
c#overridingvirtual

Using virtual and override for the same method


I want to make a method in a C# program that is overriding an existing virtual method but also keep the method virtual so any class that inherits from it can further extend the method.

Can I use both override and virtual in the method declaration? If so, which order do I put them in?

For example

public override virtual void method()

OR

public virtual override void method()

Thanks


Solution

  • This is a good post to explain what you're asking. Basically, if you make a method in your base class virtual, any derived classes will be able to override that method (no matter how deep the derivation). There is no need to continue to specify virtual for the method in your derived classes (in fact, I don't think you can do it). Use the sealed specifier to disallow the method from being overridden in derived classes.