Home > Backend Development > C++ > Virtual vs. New in C#: When to Override or Hide Base Class Methods?

Virtual vs. New in C#: When to Override or Hide Base Class Methods?

Barbara Streisand
Release: 2025-01-27 06:33:09
Original
246 people have browsed it

Virtual vs. New in C#: When to Override or Hide Base Class Methods?

Usage of virtual and new keywords in C#

In object-oriented programming, methods are usually defined in base classes and overridden or redefined in derived classes. Although both the "virtual" and "new" keywords can be used to modify method declarations, they are implemented in different ways.

virtual rewrite

  • Declare the method as "virtual" in the base class, indicating that subclasses can override it.
  • Allows derived classes to provide different method implementations without breaking the inheritance chain.

new keyword

  • Declare a new method in the derived class with the same name as the method in the base class.
  • Hide the base class method and create a new implementation in the derived class.
  • Breaks the inheritance chain, which means derived class methods have nothing to do with base class methods.

Example

Consider the following code:

<code class="language-csharp">public class Base
{
    public virtual bool DoSomething() { return false; }
}

public class Derived : Base
{
    public override bool DoSomething() { return true; }
}</code>
Copy after login

If we create an instance of Derived and store it in a variable of type Base, the call to DoSomething() will call the overridden method in Derived:

<code class="language-csharp">Base a = new Derived();
a.DoSomething(); // 返回 true</code>
Copy after login

In contrast, if we use the new keyword in Derived, the call to DoSomething() will invoke the new method in Derived, even if the variable is of type Base:

<code class="language-csharp">public class Derived : Base
{
    public new bool DoSomething() { return true; }
}</code>
Copy after login
<code class="language-csharp">Base a = new Derived();
a.DoSomething(); // 返回 true (Derived 中的新方法)</code>
Copy after login

When to use virtual override vs. new

  • Use virtual overrides to inherit and extend behavior while maintaining the inheritance chain.
  • Use new to create a new, independent implementation, thus breaking the inheritance chain.

The above is the detailed content of Virtual vs. New in C#: When to Override or Hide Base Class Methods?. For more information, please follow other related articles on the PHP Chinese website!

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