Reading the C# 6.0. book for which I am preparing a review made me think that I do not post a lot of C# code. Thus, I have decided to prepare a simple C# example of inheritance with overriding. Let’s see what would happen 🙂
Pretty much, we have 3 classes – Food, Pizza and Pepperoni.
Pepperoni is a pizza. Pizza is a food. In each class we have the method “Prepare”. In Food is says “Preparing Food.”. In Pizza, it says “Prepare Pizza”. And in Pepperoni it takes the one from the Pizza and adds “Pepperoni. This is simple enough! 🙂
Looks like this:
The code is this one:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
using System; class Food { static void Main() { Food myFood = new Food(); myFood.Prepare(); Pizza myPizza = new Pizza(); myPizza.Prepare(); Pepperoni myPepperoni = new Pepperoni(); myPepperoni.Prepare(); } public virtual void Prepare() { Console.WriteLine("Preparing Food"); } } class Pepperoni:Pizza { public override void Prepare() { Console.WriteLine(); base.Prepare(); Console.WriteLine(" Pepperoni!"); } } class Pizza : Food { public override void Prepare() { Console.Write("Prepare Pizza"); } } |
And that is enough! Mahlzeit! 🙂