0

Code:

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

    }
}

As per the definition of the 'new' modifier : "new keyword explicitly hides a member that is inherited from a base class. ". Then when we call the method with new modifier in the derived class it should always give the output as "Derived2 class", But I am always getting the output "Base Class" in all the three conditions.

        Baseclass d1 = new Derived1();
        Baseclass d2 = new Derived2();
        Baseclass b = new Baseclass();
        d1.Fun();
        d2.Fun();
        b.Fun();

Can anyone please clear my doubt?

Prateik
  • 241
  • 2
  • 6
  • 14

2 Answers2

1

It does create the correct Object but to access its specific properties, you'd need to cast it first.

Daniel van Heerden
  • 836
  • 1
  • 7
  • 25
  • Can you please explain it briefly? – Prateik Mar 17 '16 at 05:59
  • It's just polymorphism, You can assign a more specific class to its base but then you'll only be able to access the base's properties. But the Object can than be cast to its real form. Example `var castd1 = (Derived1)d1` – Daniel van Heerden Mar 17 '16 at 06:21
  • I concede my answer is partially incomplete. @paolo_montgomery_russo answer will be the reason why you are seeing the same output being written each time. – Daniel van Heerden Mar 17 '16 at 07:40
1

To get the expected behaviour you must mark method as virtual in base class and override it in subs. You declared all variables as baseclass type so baseclass method should apply.