I noticed that when overriding virtual methods in C# using Visual Studio, the IDE automatically adds the base.Method() call. On the other hand, when overriding abstract methods, the IDE automatically adds a NotImplementedException().
Why does VS automatically adds the base.Method() call when overriding virtual methods? Is it best practice to call the base method?
Yes, you need to use the override keyword, otherwise the method will be hidden by the definition in the derived class.
You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
Virtual Methods: Few Points To Remember If a method has the same definition in both the base and derived class then it's not required to override the method. Override is only required if both have a different definition.
That depends if you still need the base behaviour to occur. This decision would be made on a case by case basis. There's no hard and fast rule, although some patterns would expect a call to the base method (correct implementation of the IDisposable pattern works this way)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With