Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new Keyword and Method Hiding

Tags:

c#

inheritance

The new Keyword is used to hide the base class implementation of the same. But I am not sure why the following code produces the output as Baseclass

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(); 
    } 
} 

We are hiding the implementation of fun in derived2 but still Base class is called why so? Am I missing something?

like image 310
Programmerzzz Avatar asked May 13 '15 07:05

Programmerzzz


1 Answers

Derived2.funis private (it is the default access modifier of the members of the type). It is not visible outside the class. Only visible fun method outside the class is Baseclass.fun and thus it is invoked.

You need to make your Derived2.fun visible outside the class to get the expected output. You can do it by either making it public/internal.

like image 77
Sriram Sakthivel Avatar answered Oct 07 '22 20:10

Sriram Sakthivel