Click here to Skip to main content
15,878,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Friends,

I tried something below:

C#
class Program
    {
        static void Main(string[] args)
        {
            Program2 p2 = new Program2();
            p2.show();

            p2 = new Program3();
            p2.show();

            Console.Read();
        }

    }

   public class Program2
    {

       public virtual void show()
       {

           Console.WriteLine("Program2");

       }

    }


   public class Program3 :Program2
   {

       public new  void show()
       {
           Console.WriteLine("Program3");
       }

   }




In the above code snippet, i have used the new keyword in the Program3 class before the show() method.

Now, when i assign the object of Program2 to Program3 and call the show(), the output is always

"Program2".

I have differentiated the 2 methods, in the derived class i have used the new keyword. So my doubt is:

1>What is the significance of the new keword.
2>Why is the method of the base class called always, even though i assign the object of the base to the derived.

Thanks a ton,
Rahul
Posted
Updated 14-May-14 6:39am
v2

1 solution

new breaks polymorphism. See, for instance, Polymorphism (C# Programming Guide)[^].
 
Share this answer
 
Comments
Rahul VB 14-May-14 13:02pm    
My thanks for the solution Sir, I hope my question was not senseless. Well i dint understand how to search for it on google. Thanks again.

Thanks a Ton,
Rahul
CPallini 14-May-14 13:28pm    
You are welcome.
Maciej Los 14-May-14 15:18pm    
Short and to the point!
5!
CPallini 14-May-14 15:29pm    
Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900