Introduction
In C#, you can use inheritance to create new classes based on existing ones. When a method is defined in both the base class and the derived class, there are two ways to handle the method implementation: method overriding and method hiding.
Method Overriding
Method overriding is a feature of inheritance that allows a derived class to provide its own implementation of a method that is already defined in the base class. To override a method, you use the override
keyword in the derived class.
class ClassA
{
public virtual void T()
{
// Base implementation
}
}
class ClassB : ClassA
{
public override void T()
{
// Derived implementation
}
}
In the example above, ClassB
extends ClassA
and overrides the T
method. When you create an instance of ClassB
, calling T
will execute the implementation in ClassB
. However, if you cast the instance as ClassA
, the base implementation will be executed instead.
ClassA a = new ClassB();
a.T(); // Calls the implementation in ClassB
Method Hiding
Method hiding, on the other hand, is a concept in C# that allows a derived class to provide its own implementation of a method with the same name as a method in the base class. This hides the base class method from the derived class, and calling the method on a derived class instance will execute the derived implementation.
To hide a method, you use the new
keyword in the derived class.
class ClassA
{
public void T2()
{
// Base implementation
}
}
class ClassB : ClassA
{
public new void T2()
{
// Derived implementation
}
}
In the example above, ClassB
hides the T2
method from ClassA
. Calling T2
on an instance of ClassB
will execute the implementation in ClassB
, regardless of whether the instance is cast as ClassA
or ClassB
.
ClassA a = new ClassB();
a.T2(); // Calls the implementation in ClassA
Conclusion
Understanding the difference between method overriding and method hiding is crucial for writing effective object-oriented code in C#. By using method overriding, you can provide specialized implementations in derived classes while still benefiting from polymorphism. Method hiding, on the other hand, allows you to completely replace the implementation of a method in the derived class. Make sure to choose the right approach based on your specific requirements and design goals.
I hope this article clarifies the concepts of method overriding and method hiding in C#. If you have any further questions, please feel free to ask in the comments section below.