Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WHy should virtual methods be explicitly overridden in C#?

Why should virtual methods be explicitly overridden in C#?

like image 758
subanki Avatar asked Jul 14 '10 17:07

subanki


People also ask

Is it necessary to override a virtual method?

When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class.

Is it necessary to override a virtual method in C#?

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

Can virtual methods be overridden?

A virtual method is first created in a base class and then it is overridden in the derived class. A virtual method can be created in the base class by using the “virtual” keyword and the same method can be overridden in the derived class by using the “override” keyword.

Why do we need to override in C#?

The use of the override modifier enables bcdc to access the Method1 method that is defined in DerivedClass . Typically, that is the desired behavior in inheritance hierarchies. You want objects that have values that are created from the derived class to use the methods that are defined in the derived class.


1 Answers

By declaring a method as virtual, you are stating your intention that the method can be overridden in a derived class.

By declaring your implementing method as override, your are stating your intention that you are overriding a virtual method.

By requiring that the override keyword be used to override a virtual method, the designers of the language encourage clarity, by requiring you to state your intentions.

like image 119
Robert Harvey Avatar answered Oct 05 '22 05:10

Robert Harvey