Home > database >  If methods are neither virtual nor sealed by default, then why does this method override of a non-vi
If methods are neither virtual nor sealed by default, then why does this method override of a non-vi

Time:09-27

On several occasions, I've been told that methods in C# classes are neither sealed nor virtual by default. Despite this, the follow code works just fine and prints the two clearly intended strings. This is strong evidence that I've very confused. What default or feature am I ignorant of?

Child ExampleChild = new Child();
ExampleChild.SayHello();
Parent ExampleParent = new Parent();
ExampleParent.SayHello();

public class Parent
{
    public void SayHello() => Console.WriteLine("Hello from parent");
}
public class Child : Parent
{
    public void SayHello() => Console.WriteLine("Hello from child");
}

CodePudding user response:

You're defining a new method (Child.SayHello()), which hides the parent method. There's a compiler warning telling you so.

The new method should ideally be marked with new to make the intention clear. It won't partake in dynamic dispatch, i.e. if you have a variable of type Parent, then Parent.SayHello() will be called.

See also C# Inheritance and Member Hiding.

  • Related