Monday, 17 November 2025

Method Hiding in C#

Method Hiding in C#

Method Hiding

Method hiding occurs when a derived class defines a method with the same name as a method in the base class but uses the new keyword. The version of the method called depends on the reference type.

C# Example:

using System; class Car { public void Start() { Console.WriteLine("Car is starting."); } } class SportsCar : Car { public new void Start() { Console.WriteLine("SportsCar is starting with turbo!"); } } class Program { static void Main() { Car carRef = new Car(); carRef.Start(); SportsCar sportsCarRef = new SportsCar(); sportsCarRef.Start(); Car baseRef = new SportsCar(); baseRef.Start(); } }

Output:

Car is starting. SportsCar is starting with turbo! Car is starting.

No comments:

Post a Comment