Difference between Method Overriding and Method Hiding in C#
when I started learning C# I didn't actually get what's with this new keyword which "hide" the method. method hiding name could be confusing for non-English speaker like me, I assumed that by "hiding" it actually deletes the old method and we can no longer access it, however that's not true.
here is an example in which we are hiding a method and calling the parents method:
namespace Test
{
public class T1
{
public virtual void M()
{
System.Console.WriteLine("method from T1 class called");
}
}
public class T2 : T1
{
public new void M()
{
System.Console.WriteLine("method from T2 class called");
}
}
public class Program
{
public static void Main(string[] args)
{
T1 obj2 = new T2();
obj2.M();
}
}
}The output of this C# program will be:method from T1 class calledwhich makes sense because we are changing the type of obj from T2 to T1. so on runtime compiler will check the type of obj and call the method accordingly.
however there is something else too! you can override the method too!
take a look at the following code:
namespace Test
{
public class T1
{
public virtual void M()
{
System.Console.WriteLine("method from T1 class called");
}
}
public class T2 : T1
{
public override void M()
{
System.Console.WriteLine("method from T2 class called");
}
}
public class Program
{
public static void Main(string[] args)
{
T1 obj2 = new T2();
obj2.M();
}
}
}now since we have overridden the method the old method has been replaced by new method in both T1 and T2 classes. ( by default c# compiler hides the method )
so yeah that is the difference between Method Overriding and Method Hiding.
Comments
Post a Comment