πŸ”Ή C# Tip: Understanding override, new, and virtual Keywords



This content originally appeared on DEV Community and was authored by DotNet Full Stack Dev

In C#, when dealing with class inheritance, you can use virtual, override, and new to control how methods and properties behave in derived classes. Understanding their differences can help you design your classes more effectively.

📌Explore more at: https://dotnet-fullstack-dev.blogspot.com/
🌟 Sharing would be appreciated! 🚀

public class BaseClass
{
    // Virtual method, can be overridden in derived classes
    public virtual void Display()
    {
        Console.WriteLine("Display from BaseClass");
    }

    // Hides the method in the derived class
    public virtual void Show()
    {
        Console.WriteLine("Show from BaseClass");
    }
}

public class DerivedClass : BaseClass
{
    // Overrides the virtual method
    public override void Display()
    {
        Console.WriteLine("Display from DerivedClass");
    }

    // Hides the Show method without overriding
    public new void Show()
    {
        Console.WriteLine("Show from DerivedClass");
    }
}

🔍 Key Points:

virtual: Allows a method to be overridden in derived classes.
override: Implements the method defined as virtual in the base class.
new: Hides the base class member. It doesn’t override the base implementation, which still exists.
Usage:

BaseClass obj = new DerivedClass();
obj.Display(); // Output: Display from DerivedClass
obj.Show();    // Output: Show from BaseClass

This illustrates how you can effectively use these keywords to control method behavior and achieve polymorphism.


This content originally appeared on DEV Community and was authored by DotNet Full Stack Dev