This week I have started again to look into Object Oriented Programming with C#. Thus, I have built a small example of OOP, using Enumeration.
In the example I have two classes – the class “RunningCar”, containing the Main method and the class “SpeedCar”, defining the property speed, with a constructor and a getter.
Finally the result of the code is the following 🙂 :
Let’s see what we have in the code:
- The enumeration part
1 2 3 4 5 6 |
public enum VehicleSpeed { InTown = 50, OutOfTown = 90, OnHighway = 130 } |
- Public Class with the property, the builder and the getter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class SpeedCar { public VehicleSpeed speed; public SpeedCar(VehicleSpeed speed) { this.speed = speed; } public VehicleSpeed Speed { get { return speed; } } } |
- Finally the second class, containing the Main method, in which we define two objects – a Ferrari with enum “InTown” and Audi with enum OutOfTown. I hope you get the idea:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class RunningCar { static void Main() { SpeedCar Ferrari = new SpeedCar(VehicleSpeed.InTown); SpeedCar Audi = new SpeedCar(VehicleSpeed.OutOfTown); Console.WriteLine("The {0} speed {1} km per hour.", VehicleSpeed.InTown, (int)VehicleSpeed.InTown); Console.WriteLine("The {0} speed {1} km per hour.", VehicleSpeed.OutOfTown, (int)VehicleSpeed.OutOfTown); } } |
The whole code is located here:
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 |
using System; public enum VehicleSpeed { InTown = 50, OutOfTown = 90, OnHighway = 130 } public class SpeedCar { public VehicleSpeed speed; public SpeedCar(VehicleSpeed speed) { this.speed = speed; } public VehicleSpeed Speed { get { return speed; } } } public class RunningCar { static void Main() { SpeedCar Ferrari = new SpeedCar(VehicleSpeed.InTown); SpeedCar Audi = new SpeedCar(VehicleSpeed.OutOfTown); Console.WriteLine("The {0} speed {1} km per hour.", VehicleSpeed.InTown, (int)VehicleSpeed.InTown); Console.WriteLine("The {0} speed {1} km per hour.", VehicleSpeed.OutOfTown, (int)VehicleSpeed.OutOfTown); } } |
Enjoy it! 🙂