Skip to main content
edited body
Source Link
Rob
  • 27.5k
  • 16
  • 89
  • 103

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, butnot 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" + " "); } 

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, but 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" + " "); } 

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" + " "); } 
Source Link
Rob
  • 27.5k
  • 16
  • 89
  • 103

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, but 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" + " "); }