Why does not call parent method when we don't use method hiding?
c#, method-hiding
Solution
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");
}
Problem
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?