1

Why does this code produce the output "Base class" and not "Derived2 class"?

namespace TestConsoleApplication { class Baseclass { public void fun() { Console.Write("Base class" + " "); } } class Derived1: Baseclass { new void fun() { Console.Write("Derived1 class" + " "); } } class Derived2: Derived1 { new void fun() { Console.Write("Derived2 class" + " "); } } class Program { public static void Main(string[ ] args) { Derived2 d = new Derived2(); d.fun(); } } } 
1
  • 2
    Because public void fun is not virtual and not overridden in derived classes. Commented Jun 3, 2016 at 5:23

1 Answer 1

4

Because you didn't declare the method as public.

You've told it to hide the original definition, rather than override it - which it will do, but the default access modifier is private, not public.

For example, when calling the method from within Derived2:

class Derived2 : Derived1 { new void fun() { Console.Write("Derived2 class" + " "); } public void Test() { fun(); } } class Program { public static void Main(string[] args) { Derived2 d = new Derived2(); d.Test(); //Prints 'Derived2 class' } } 

Setting it to public will indeed print Derived2 in your original example

public new void fun() { Console.Write("Derived2 class" + " "); } 
Sign up to request clarification or add additional context in comments.

1 Comment

I would read it for ever, not seeing that access modifiers are missing. Good job Rob.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.