Home >Backend Development >C++ >What's the Difference Between `new` and `override` Keywords for Methods in C# Inheritance?

What's the Difference Between `new` and `override` Keywords for Methods in C# Inheritance?

DDD
DDDOriginal
2025-01-28 12:01:09856browse

What's the Difference Between `new` and `override` Keywords for Methods in C# Inheritance?

and new override In object -oriented programming, inheritance allows the function of inheritance and expansion of the base class. When defining methods in derivatives, developers often use keywords "New" and "Override". Although these two keywords seem to have similar effects, their purpose is very different.

Situation 1:

Keywords

new The method of the keyword represents the derived class is a new method, which has nothing to do with any method in the base class. Even if the base class has the same name, the method will have a separate implementation of the derived class.

Situation 2: new Keywords new

On the other hand, The keywords indicate the implementation of the same method in the base class. The compiler ensures that the method will use the latest implementation of the inheritance chain, even if the object is referenced by the base class reference. override Behavioral differences

The key difference between

and override is how they handle the method call. If the override method is called on the base class reference, it will execute the implementation of the derivative class. However, if the method is called, it will implement the implementation of the derived class, regardless of the type of reference.

Grammar example

The following code demonstrates the difference between

and new: override new override In this example, calling () to perform the implementation of the Derived class on the object of the derived type. However, calling () to perform the original implementation in the base () on objects of the base type, because Derived.Doit () is a new method.

Use cases

new : override When the derivative class needs to be fully used compared to the base class, it is used when it is fully different from the base class.

<code class="language-csharp">public class Base
{
    public virtual void DoIt() { }
}

public class Derived : Base
{
    public new void DoIt() { } // 新的实现
}</code>

:

When the derivative classes want to provide different or improved methods to inherit the self -based class, use it.

The above is the detailed content of What's the Difference Between `new` and `override` Keywords for Methods in C# Inheritance?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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