What is the output class BC { public void Display() { System.Console.WriteLine("BC::Display"); } } class DC : BC { new public void Display() { System.Console.WriteLine("DC::Display"); } } class Demo { public static void Main() { BC b; b = new BC(); b.Display(); b = new DC(); b.Display(); } }
Here we are creating an object of Derived class DC and storing its reference in the reference variable b of type BC. This is valid in C#. Next, using the reference variable b we invoke the function Display(). Since b contains a reference to object of type DC one would expect the function Display() of class DC to get executed. But that does not happen. Instead what is executed is the Display() of BC class. That's because the function is invoked based on type of the reference and not to what the reference variable b refers to. Since b is a reference of type BC, the function Display() of class BC will be invoked, no matter whom b refers to.
The new modifier instructs the compiler to use your child class implementation instead of the parent class implementation.
Answer has been verified