"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2025-01-29
Browse:113

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

The usage of virtual and new keywords in

in C# In object -oriented programming, it is usually defined in the base class, and these methods are rewritten or redefined in the derivative class. Although both "Virtual" and "New" keywords can be used to modify the method declaration, they have different implementation methods.

dirtual rewriting

The method declared in the base class as "virtual", indicating that subclasses can be rewritten.

    Allow derived classes to provide different methods for implementation without destroying the inheritance chain.
  • New keyword

State a new method of the same name as the foundation Chinese method in the derivative class.

Hide the basic method and create a new implementation in the derived class.
  • Destroy the inheritance chain, which means that the derived method is not related to the base method.
  • Example
Consider the following code:

Public Class Base {{ public virtual bool dosomething () {Return false;} } Public class derived: base: base {{ Public override bool dosomething () {Return True;} }

If we create a Derived instance and store it in the base type variable, the call for Dosomething () will call the method of rewriting in Derived:

public class Base
{
    public virtual bool DoSomething() { return false; }
}

public class Derived : Base
{
    public override bool DoSomething() { return true; }
}
On the contrary, if we use the new keyword in Derived, the call for dosomething () will call a new method in Derived. Even if the variable is Base type:

Base a = new Derived();
a.DoSomething(); // 返回 true

base a = new derived (); a.dosomething (); // Return to True (new method in derived)

public class Derived : Base
{
    public new bool DoSomething() { return true; }
}
Base a = new Derived();
a.DoSomething(); // 返回 true (Derived 中的新方法)

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3