Click here to Skip to main content
14,667,169 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hello Friends,

I tried something below:

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

Rate this:
Please Sign up or sign in to vote.

Solution 1

new breaks polymorphism. See, for instance, Polymorphism (C# Programming Guide)[^].
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100