1

So I have this hierarchy:

enter image description here

They all have a method called helloWorld:

class A{

public virtual void helloWorld(){
    Console.WriteLine("Hello, I am class A!");
...
}

class B:A{

public override void helloWorld(){
    Console.WriteLine("Hello, I am class B!");
...
}

class C:B{

public new void helloWorld(){
    Console.WriteLine("Hello, I am class C!");
...
}

It sounds reasonable to me that this code:

A a = new B();
a.helloWorld();

returns "Hello, I am class B!". Compiler gave priority to the most specific class implementation referenced.

But I can't understand why this code:

A a = new C();
a.helloWorld();

return "Hello, I am class B!", if no reference to class B has ever been made. Does any C# documentation explain the reason for that behaviour?

Edit: I think I got the concept of shadowing, but I still can't see why a non-referenced class is being called.

Mr Guliarte
  • 739
  • 1
  • 10
  • 27
  • 2
    You get the `B` implementation because `C` inherited it. The `new` method in `C` is simply not an implementation of `HelloWorld` and can therefore never be called through `A`. That's why you're required to write `new` in the first place, to show that you know what you're doing in *not* overriding the method. It's exactly the same as if you'd given the method a completely unrelated name (like `HelloWorldC`) without `new`. The only way to call this method is through a variable of type `C`, which `a` is not. – Jeroen Mostert Jan 18 '23 at 20:42
  • This is exactly the answer I was looking for. Thank you a lot! – Mr Guliarte Jan 20 '23 at 14:11

0 Answers0