//Classic sample of Polymorphism 4 Knowing When to Use Override and New Keywords public static void ScenarioEight() { Teacher baseTeacher = new Teacher(); baseTeacher.ShowMeDance(); System.Console.WriteLine("----------"); NewStyleTeacher newStyleTeacher = new NewStyleTeacher(); newStyleTeacher.ShowMeDance(); //go to the new newStyleTeacher.Dance(); ///go to the new System.Console.WriteLine("----------"); BachataTeacher bachataTeacher = new BachataTeacher(); bachataTeacher.ShowMeDance(); //go to base System.Console.WriteLine("----------"); StupidTeacher stupidTeacher = new StupidTeacher(); stupidTeacher.ShowMeDance(); //go to the old // Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
//Calls with cast implicit Knowing When to Use Override and New Keywords // "new" keyword is specified, the compiler will issue a warning and the method //in the derived class will hide the method in the base class. public static void ScenarioNine() { var derived = new NewStyleTeacher(); derived.Dance(); ((Teacher)derived).Dance(); //Call old method-----new System.Console.WriteLine("----------"); var derived2 = new BachataTeacher(); derived2.Dance(); ((Teacher)derived2).Dance(); //Call new method-----------override // Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
//Classic sample of Polymorphism 2 // Virtual methods and properties enable derived classes to extend a base class without // needing to use the base class implementation of a method public static void ScenarioFive() { BachataTeacher B = new BachataTeacher(); B.Dance(); // Calls the new method. Teacher A = (Teacher)B; A.Dance(); // Also calls the new method. Teacher D = new BachataTeacher(); D.Dance(); // Also calls the new method. // Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }