Home > Backend Development > C++ > Virtual/Override vs. New in C#: When Should I Use Which Keyword for Method Overriding?

Virtual/Override vs. New in C#: When Should I Use Which Keyword for Method Overriding?

Linda Hamilton
Release: 2025-01-27 06:36:09
Original
432 people have browsed it

Virtual/Override vs. New in C#: When Should I Use Which Keyword for Method Overriding?

Virtual/Override and New Keywords in the C#: When to use which keywords to rewrite the method?

When defining methods in the base class, programmers often face the problem of whether to use "virtual" or "new" keywords. This decision will significantly affect the rewriting of the derived Chinese law.

Virtual override

The "virtual" keyword in the base method indicates that it can be rewritten in the derived class. To rewrite this method, the derived class must use the "Override" keyword. This ensures that the rewriting method is working as expected to maintain the hierarchical structure and polymorphism. When the method of calling and rewrite by the derivative class calls, it will execute the rewriting version, even if the reference variable of the holding object is the base class. This is called post -binding and allows dynamic behavior.

New keyword

On the contrary, the "NEW" keyword in the derived method declares a new method that hides the inheritance method with the same name. When using, the new method replaces the inheritance method in the derived class, thereby destroying polymorphism.

When the derived class calls the method of "New" statement, it will execute the new method, regardless of the type of reference variables of the holding object. This is considered to be early binding and hinders polymorphism.

Example

Consider the following code example:

If you allocate the examples of the derived to the base variable and call the dosomething (), if you use Virtual/Override, the result will be false, but if you use it, the result is true. This highlights the difference between later binding and early binding.

The above is the detailed content of Virtual/Override vs. New in C#: When Should I Use Which Keyword for Method Overriding?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template