Sobes.tech
Middle

What is the difference between overriding and hiding methods in C#?

sobes.tech AI

Answer from AI

Override is used to implement polymorphism, allowing a derived class to provide its own implementation of a virtual, abstract, or inherited method. The keywords virtual in the base class and override in the derived class are mandatory.

Hiding (shadowing) is when a method with the same name in the derived class hides a method from the base class. The base class method remains, but access to it from an instance of the derived class is through explicit casting or the base keyword. The new keyword is used in the derived class.

Attribute Override Hiding (Shadowing)
Keyword virtual (base), override (derived) new (derived)
Polymorphism Yes, the derived class implementation is called No, the method called depends on the reference type
Call by base reference Calls the overridden method of the derived class Calls the base class method
Access to base method Via base.MethodName() Via base.MethodName() or casting
public class BaseClass
{
    public virtual void ShowMessage() // Virtual method for overriding
    {
        Console.WriteLine("Message from BaseClass (virtual).");
    }

    public void DisplayInfo() // Method for hiding
    {
        Console.WriteLine("Info from BaseClass.");
    }
}

public class DerivedClass : BaseClass
{
    public override void ShowMessage() // Overriding virtual method
    {
        Console.WriteLine("Message from DerivedClass (override).");
    }

    public new void DisplayInfo() // Hiding method
    {
        Console.WriteLine("Info from DerivedClass (new).");
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        BaseClass baseObj = new BaseClass();
        DerivedClass derivedObj = new DerivedClass();
        BaseClass derivedAsBase = new DerivedClass(); // Base type reference to derived object

        baseObj.ShowMessage();     // Output: Message from BaseClass (virtual).
        baseObj.DisplayInfo();     // Output: Info from BaseClass.

        derivedObj.ShowMessage();  // Output: Message from DerivedClass (override).
        derivedObj.DisplayInfo();  // Output: Info from DerivedClass (new).

        derivedAsBase.ShowMessage(); // Output: Message from DerivedClass (override). (Polymorphism in action)
        derivedAsBase.DisplayInfo(); // Output: Info from BaseClass. (BaseClass method called due to reference type)
    }
}