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
DotNet Full Stack Dev | Sciencx (2024-10-22T17:39:11+00:00) 🔹 C# Tip: Understanding override, new, and virtual Keywords. Retrieved from https://www.scien.cx/2024/10/22/%f0%9f%94%b9-c-tip-understanding-override-new-and-virtual-keywords/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.