0

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

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • I'm pretty sure if you are overriding a method, it is already virtual – Andrew Williamson Mar 30 '18 at 04:09
  • you have use "public override void method()" in sub child class like the way you override method in child class. Read on the [article](https://www.codeproject.com/Articles/18734/Method-Overriding-in-C) for more detail. – tiennguyen Mar 30 '18 at 04:24

2 Answers2

2

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.

Cory
  • 783
  • 5
  • 12
  • Thanks you that makes so much more sense. Its nice that the language provides so much functionality for handling these specific circumstances – Will Bowden Mar 30 '18 at 05:04
1

If a method is virtual, any child class can override it. You do not need to redeclare it as virtual.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual

jcwmoore
  • 1,153
  • 8
  • 13