Consider this code:
internal class Program
{
private static void Main(string[] args)
{
var student = new Student();
student.ShowInfo(); //output --> "I am Student"
}
}
public class Person
{
public void ShowInfo()
{
Console.WriteLine("I am person");
}
}
public class Student : Person
{
public void ShowInfo()
{
Console.WriteLine("I am Student");
}
}
in above code we don't use method hiding.
when create instance of student and call showinfo
method my output is I am Student
i don't use new
keyword.
Why does not call parent method when we don't use method hiding?
In method hiding, you can hide the implementation of the methods of a base class from the derived class using the new keyword. Or in other words, in method hiding, you can redefine the method of the base class in the derived class by using the new keyword.
For Method overriding override keyword is being used. In case of Method Hiding new keyword is used to define new implementation in child class. In Method Overriding the implementation type of the method is of object type. However on other hand implementation type of method in Method hiding is of reference type.
Method hiding is also known as shadowing. The method of the parent class is available to the child class without using the override keyword in shadowing. The child class has its own version of the same function. Use the new keyword to perform shadowing.
No matter whether you are using the new
keyword or not the base method is not virtual. So it is always the derived method that will get called. The only difference is that the compiler emits you a warning because the base method is hidden and you didn't explicitly used the new
keyword:
'Student.ShowInfo()' hides inherited member 'Person.ShowInfo()'. Use the new keyword if hiding was intended.
The C# compiler is emitting this to warn you that you might have by mistake done that without even realizing it.
In order to fix the warning you should use the new keyword if this hiding was intentional:
public new void ShowInfo()
{
Console.WriteLine("I am Student");
}
If not, you should make the base method virtual:
public class Person
{
public virtual void ShowInfo()
{
Console.WriteLine("I am person");
}
}
and then override it in the derived class:
public class Student : Person
{
public override void ShowInfo()
{
Console.WriteLine("I am Student");
}
}
Obviously in both cases you have the possibility to call the base method if you want that:
public override void ShowInfo()
{
base.ShowInfo();
Console.WriteLine("I am Student");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With