Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When overriding virtual methods, is it best practice to call the base method? [closed]

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?

like image 803
Ian Avatar asked Nov 21 '11 13:11

Ian


People also ask

Is it mandatory to override virtual methods of base class?

Yes, you need to use the override keyword, otherwise the method will be hidden by the definition in the derived class.

Can you override a virtual method?

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.

Is it necessary to override a virtual method?

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.


1 Answers

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)

like image 135
spender Avatar answered Oct 05 '22 23:10

spender