Home >Backend Development >C++ >Override vs. New in C#: When Should You Use Each Keyword to Modify Inherited Methods?
Understand Override and New Keywords in C#: When to use them to modify the inheritance method?
In object -oriented programming, the foundation method in the inheritance class is very important. "Override" and "New" keywords have different uses in this context:
<.> 1. Override keyword
"Override" modifier is used to explicitly rewrite the virtual method or abstract method in the base class. When the rewriting method, it provides a new implementation, while retaining the signature of the original method. Whenever you call this method, even if you reference to the base class, the rewriting method will be performed. <.> 2. NEW keyword
"NEW" modifier represents a different implementation method. It has the same name as the base method, but it is actually a new method. The "New" method will shield the foundation method, which means that any coding of the base class will execute the original implementation, and the code that quotes the inheritance class will execute the "New" method.
Example:
Consider the following code fragment:
In this example, the "Derived" class rewritten the "Doit" method. Any reference to "Base.Doit" will execute the "doit" method in the "Derived" class.
In this case, "Doit" in the "Derived" class is considered a new method. The reference to "Base.doit" will perform the original implementation of the "Base" class, and the reference to "Derived.Doit" will perform new implementation in the "Derived" class.Recommended usage:
<code class="language-C#">public class Base { public virtual void DoIt() { } } public class Derived : Base { public override void DoIt() { } }</code>
When rewriting methods, it is recommended to use "Override" because it retains the method signature and allows polymorphism. On the other hand, "NEW" is used to create different methods from the base class, which may destroy the inheritance relationship.
<code class="language-C#">public class Base { public virtual void DoIt() { } } public class Derived : Base { public new void DoIt() { } }</code>
The above is the detailed content of Override vs. New in C#: When Should You Use Each Keyword to Modify Inherited Methods?. For more information, please follow other related articles on the PHP Chinese website!