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

dotnetfullstackdev

DotNet Full Stack Dev

Posted on October 22, 2024

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

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");
    }
}

Enter fullscreen mode Exit fullscreen mode

πŸ” 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

Enter fullscreen mode Exit fullscreen mode

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

πŸ’– πŸ’ͺ πŸ™… 🚩
dotnetfullstackdev
DotNet Full Stack Dev

Posted on October 22, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related