Skip to main content

C# Method Hiding

Introduction

When working with inheritance in C#, you'll encounter situations where you need to redefine methods that already exist in a base class. C# provides two primary mechanisms for this: method overriding and method hiding.

While overriding is more commonly used, method hiding is an important concept to understand as it behaves differently and serves different purposes. Method hiding allows a derived class to implement a method with the same name as a method in the base class, effectively "hiding" the base class implementation rather than replacing it.

In this tutorial, we'll explore method hiding in depth, understand when to use it, and how it differs from method overriding.

Method Hiding vs. Method Overriding

Before diving into method hiding, let's clarify the key differences between hiding and overriding:

FeatureMethod HidingMethod Overriding
Keywordnewoverride
Base requirementNo special modifier needed in base classMethod must be virtual, abstract, or already override
Runtime behaviorUses the static type for method resolutionUses the actual object type for method resolution
Design intent"I'm providing a new implementation, unrelated to the base class""I'm extending or modifying the base class behavior"

How to Implement Method Hiding in C#

To hide a method from a base class, you use the new keyword in the method declaration.

csharp
public class BaseClass
{
public void Display()
{
Console.WriteLine("This is the Display method from BaseClass");
}
}

public class DerivedClass : BaseClass
{
// Using 'new' keyword to hide the base class method
public new void Display()
{
Console.WriteLine("This is the Display method from DerivedClass");
}
}

Method Hiding Behavior

Let's see how method hiding behaves at runtime:

csharp
class Program
{
static void Main(string[] args)
{
// Create instances
BaseClass baseObj = new BaseClass();
DerivedClass derivedObj = new DerivedClass();
BaseClass baseRefToChild = new DerivedClass();

// Call methods
baseObj.Display(); // Calls BaseClass.Display()
derivedObj.Display(); // Calls DerivedClass.Display()
baseRefToChild.Display(); // Calls BaseClass.Display() - This is key!

Console.ReadKey();
}
}

Output:

This is the Display method from BaseClass
This is the Display method from DerivedClass
This is the Display method from BaseClass

Notice how the last call uses the method from BaseClass even though the actual object is a DerivedClass. This is the defining characteristic of method hiding: the method that gets called depends on the reference type, not the object type.

When to Use Method Hiding

Method hiding is useful in specific scenarios:

  1. When you want to completely replace functionality without respecting the base class contract
  2. When the base class method isn't virtual but you still need to provide a different implementation
  3. When you want to implement a method from an interface that's already implemented in the base class, but with different logic

Example: Implementing an Interface

csharp
public interface IDisplayable
{
void Display();
}

public class BaseClass
{
public void Display()
{
Console.WriteLine("BaseClass: Standard display method");
}
}

// Need to implement IDisplayable, but BaseClass already has a Display method
public class DerivedClass : BaseClass, IDisplayable
{
// Using method hiding to satisfy the interface
public new void Display()
{
Console.WriteLine("DerivedClass: Implementing IDisplayable interface");
}
}

Accessing the Hidden Method

Sometimes you might want to access the hidden base class method from the derived class:

csharp
public class DerivedClass : BaseClass
{
public new void Display()
{
Console.WriteLine("This is the Display method from DerivedClass");

// Call the hidden base class method
base.Display();
}
}

When executed, this would output:

This is the Display method from DerivedClass
This is the Display method from BaseClass

Real-World Example: Custom Controls

Method hiding is often used when implementing custom controls where you need to change behavior fundamentally:

csharp
public class StandardButton
{
public void Click()
{
Console.WriteLine("Standard button clicked");
PerformAction();
}

public void PerformAction()
{
Console.WriteLine("Performing standard action");
}
}

public class CustomButton : StandardButton
{
// Hide the base class method with completely different implementation
public new void Click()
{
Console.WriteLine("Custom button clicked");
LogActivity();
PerformCustomAction();
}

private void LogActivity()
{
Console.WriteLine("Logging button activity");
}

private void PerformCustomAction()
{
Console.WriteLine("Performing specialized action");
}
}

Notice how CustomButton.Click() doesn't call the base class implementation at all - it's a completely different implementation.

Compiler Warnings

If you don't use the new keyword when hiding a method, the C# compiler will issue a warning:

warning CS0108: 'DerivedClass.Display()' hides inherited member 'BaseClass.Display()'.
Use the new keyword if hiding was intended.

Always use the new keyword explicitly to show that you intend to hide the base class member.

Method Hiding vs. Overriding: Choosing the Right Approach

As a rule of thumb:

  • Use overriding when extending or modifying a base class behavior while maintaining its contract
  • Use hiding when implementing a completely different behavior that shouldn't be polymorphic

Let's demonstrate both approaches:

csharp
public class Shape
{
// Can be overridden
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}

// Cannot be overridden (no virtual keyword)
public void Describe()
{
Console.WriteLine("This is a general shape");
}
}

public class Circle : Shape
{
// Overriding - extends the base functionality
public override void Draw()
{
Console.WriteLine("Drawing a circle");
}

// Hiding - completely different implementation
public new void Describe()
{
Console.WriteLine("This is a circle with radius R");
}
}

Testing this code:

csharp
static void Main()
{
// Through base class reference
Shape shape = new Circle();
shape.Draw(); // Output: "Drawing a circle" (overridden)
shape.Describe(); // Output: "This is a general shape" (hidden, base method called)

// Through derived class reference
Circle circle = new Circle();
circle.Draw(); // Output: "Drawing a circle"
circle.Describe(); // Output: "This is a circle with radius R"
}

Summary

Method hiding in C# allows you to provide a new implementation of a method that exists in a base class. Unlike overriding, which is resolved at runtime based on the object's type, method hiding is resolved at compile-time based on the reference type.

Key points to remember:

  • Use the new keyword to hide a base class method
  • Method hiding is based on the reference type, not the object type
  • Use method hiding when you need a completely different implementation
  • It's often necessary when implementing interfaces already implemented in a base class
  • Method hiding doesn't require the base method to be marked as virtual

Understanding method hiding gives you more flexibility in your object-oriented design, allowing you to handle cases where traditional polymorphism via overriding isn't suitable.

Exercises

  1. Create a base Calculator class with methods Add() and Subtract(). Then create a ScientificCalculator class that hides these methods and implements them differently.

  2. Build a class hierarchy with Animal, Bird, and Penguin classes where Bird overrides the Move() method from Animal to implement flying, but Penguin hides the Move() method from Bird to implement waddling instead.

  3. Experiment with a mix of hiding and overriding in a three-level class hierarchy. Observe how method calls behave with different reference types.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)