πΉ C# Tip: Understanding override, new, and virtual Keywords
DotNet Full Stack Dev
Posted on October 22, 2024
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.
Posted on October 22, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.