Created
November 16, 2011 08:15
-
-
Save allomov/1369554 to your computer and use it in GitHub Desktop.
C# is funny (difference between override and new)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Define the base class | |
class Car | |
{ | |
public virtual void DescribeCar() | |
{ | |
System.Console.WriteLine("Four wheels and an engine."); | |
} | |
} | |
// Define the derived classes | |
class ConvertibleCar : Car | |
{ | |
public new virtual void DescribeCar() | |
{ | |
base.DescribeCar(); | |
System.Console.WriteLine("A roof that opens up."); | |
} | |
} | |
class Minivan : Car | |
{ | |
public override void DescribeCar() | |
{ | |
base.DescribeCar(); | |
System.Console.WriteLine("Carries seven people."); | |
} | |
} | |
public static void TestCars1() | |
{ | |
System.Console.WriteLine("Test Case 1 >>>"); | |
Car car1 = new Car(); | |
car1.DescribeCar(); | |
System.Console.WriteLine("----------"); | |
ConvertibleCar car2 = new ConvertibleCar(); | |
car2.DescribeCar(); | |
System.Console.WriteLine("----------"); | |
Minivan car3 = new Minivan(); | |
car3.DescribeCar(); | |
System.Console.WriteLine("----------"); | |
} | |
public static void TestCars2() | |
{ | |
System.Console.WriteLine("Test Case 2 >>>"); | |
Car[] cars = new Car[3]; | |
cars[0] = new Car(); | |
cars[1] = new ConvertibleCar(); | |
cars[2] = new Minivan(); | |
foreach (Car vehicle in cars) | |
{ | |
System.Console.WriteLine("Car object: " + vehicle.GetType()); | |
vehicle.DescribeCar(); | |
System.Console.WriteLine("----------"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Test Case 1 >>> | |
Four wheels and an engine. | |
---------- | |
Four wheels and an engine. | |
A roof that opens up. | |
---------- | |
Four wheels and an engine. | |
Carries seven people. | |
---------- | |
Test Case 2 >>> | |
Car object: YourApplication.Car | |
Four wheels and an engine. | |
---------- | |
Car object: YourApplication.ConvertibleCar | |
Four wheels and an engine. | |
---------- | |
Car object: YourApplication.Minivan | |
Four wheels and an engine. | |
Carries seven people. | |
---------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment