Hiding vs. Overriding a Method
Explore the key differences between method hiding and overriding in C#. Understand how to use the new keyword to hide base class methods, and how virtual methods enable runtime polymorphism through overriding. This lesson helps you grasp the practical implications of method resolution and inheritance when designing classes in C#.
We'll cover the following...
Hiding defines a method in a derived class that shares the name and signature of a method in the base class.
Unlike overriding, which modifies the implementation of an existing virtual method, hiding creates a distinct method that functions independently of the base version. To explicitly declare that we intend to hide a method, we use the new keyword.
We begin by defining a base class that contains the method we intend to hide.
Line 1: We declare a file-scoped namespace, reducing indentation for the rest of the file.
Line 3: We define a public class
Animal.Line 6: We define a public method named
Voice.Line 8: We print a generic animal sound to the console.
Next, we define the derived Bird class. In this initial step, we will define a Voice method with the exact same signature as the base class, but without using any special keywords.