Home >Backend Development >C++ >Overriding vs. Hiding in C#: What's the Difference?

Overriding vs. Hiding in C#: What's the Difference?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-18 08:32:09123browse

Overriding vs. Hiding in C#: What's the Difference?

Method overriding and method hiding in C#

In C#, method overriding and method hiding are two different mechanisms for modifying inherited methods.

Method Overriding

Method overriding involves creating a virtual method in the base class and redefining its implementation in the derived class. This allows derived classes to provide more specific or modified versions of methods while retaining the same method names and parameters.

Method overriding is used in the following situations:

  • You want the derived class to provide custom implementations of methods inherited from the base class.
  • Base class methods are marked virtual.
  • Use the override keyword in method declarations in derived classes.

Method Hiding

Method hiding involves creating a new method (new) with the same name and parameters as the base class method. Unlike method overriding, method hiding creates a completely new method in the derived class and does not modify the base class method.

Method hiding is used in the following situations:

  • You want to introduce a different method in the derived class with the same name as the base class method.
  • Methods in base classes are not declared as virtual.
  • Use the new keyword in method declarations in derived classes.

Practical Application

Method Overriding:

  • Custom inherited methods
  • Provide polymorphic behavior

Method Hiding:

  • Forward compatibility (avoiding problems when new methods are added in the future)
  • Covariance of return types (returning derived class instances from base class methods)

Example

The following example demonstrates method overriding and method hiding:

<code class="language-csharp">class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Generic animal sound");
    }
}

class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Bark");
    }

    public new void Run()   // 方法隐藏
    {
        Console.WriteLine("Dog running");
    }
}</code>

In this example, the MakeSound method is overridden in the Dog class to provide a concrete implementation. The Run method is hidden and a new method is created in the Dog class.

The above is the detailed content of Overriding vs. Hiding in C#: What's the Difference?. 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