In this article, we will learn an Inheritance in c# with example real-time by using windows application from scratch
Go to visual studio ⭢ select windows application ⭢ Name: vechileUsingInheritance

Right Click on Solution ⭢ Add ⭢ Class name as Vehicle

Change the vehicle class as an abstract class and add inside the two classes Truck and Car.
Vehicle class is parent class and the car is a child class, under the parent class vehicle we have different types of child vehicles like a car, truck, bike lorry …etc
all child class vehicles have common functionality like start, escalator, breaks, stop, ..etc
The common functionality ( start, escalator, breaks, stop, ..etc ) we will put inside vehicle class and then we will implement in derived child class like car, truck..etc
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VehicleAssignment { public enum Color { White = 0, Black, Red, Grey, Brown } abstract class Vehicle { public string TypeOfVehicle; public string RegNo; public static int _PrevId; private int _VehicleId; public int VehicleId { get { return _VehicleId; } } public string Make; public string Model; public Color Color; public decimal Price; protected decimal _CurrentPrice; public decimal CurrentPrice { get { _CurrentPrice = Price; int difference = DateTime.Now.Year - DateOfManufacture.Year; if (difference < Car.ServiceYear) { for (int i = 1; i <= difference; i++) { _CurrentPrice = (_CurrentPrice - (_CurrentPrice / 10)); } } else { _CurrentPrice = 0; } return _CurrentPrice; } } public int Speed; public abstract int MaxAccelerate { get; set; } public static int MinDeaccelerate = 10; public static int ServiceYear = 15; public DateTime DateOfManufacture; protected string _Status; public string Status { get { return _Status; } } public Vehicle() { _PrevId++; _VehicleId = _PrevId; } public Vehicle(string regNo, string typeOfVehicle, string make, string model, Color color, decimal price, DateTime dateOfManufacture) : this() { this.RegNo = regNo; this.Make = make; this.Model = model; this.Color = color; this.Price = price; this.DateOfManufacture = dateOfManufacture; this.TypeOfVehicle = typeOfVehicle; } public abstract void Start(); public abstract void Stop(); public abstract void Accelerate(int offsetSpeed); public void DeAccelerate(int offsetSpeed) { if (offsetSpeed < MinDeaccelerate) { throw new ApplicationException("Your car is going to stop"); } if (Speed <= 10) { throw new ApplicationException("Max speed of Car cannot be accelerate"); } Speed -= offsetSpeed; _Status = "Your Car has slow down at speed 10 and current spped is" + Speed; } } class Car : Vehicle { private int _MaxAccelerate = 10; public override int MaxAccelerate { get { return _MaxAccelerate; } set { _MaxAccelerate = value; } } public Car() { //default constructor } public Car(string regNo, string typeOfVehicle, string make, string model, Color color, decimal price, DateTime dateofmanufacture) : base(regNo, typeOfVehicle, make, model, color, price, dateofmanufacture) { if ((DateTime.Now.Year - this.DateOfManufacture.Year) == 0) { _Status = "Congratulations on Purchasing a new Car"; } else { _Status = "Your current price of the vehicle is:" + CurrentPrice; } //this.Status = "Congratulations on buying a new car"; } public override void Start() { Speed = 20; _CurrentPrice = Price; int difference = DateTime.Now.Year - this.DateOfManufacture.Year; if (difference > Vehicle.ServiceYear) { throw new ApplicationException("Car Expired"); } _Status = "car started at the speed of 20"; } public override void Stop() { Speed = 0; _Status = "Your Car stopped at the speed of" + Speed; } public override void Accelerate(int offsetSpeed) { if (offsetSpeed < MaxAccelerate) { throw new ApplicationException("Your Car cannot start"); } if (Speed >= 140) { throw new ApplicationException("Car cannot cross beyond Max Speed"); } Speed += offsetSpeed; _Status = "Your car started at speed of 20 and current speed is: " + Speed; } public override string ToString() { return "Your Car is running at the Speed" + Speed + "\r\n Color:" + Color + "\r\n Make:" + Make + "\r\n Model:" + Model; } } class Truck : Vehicle { private int _MaxAccelerate = 120; public override int MaxAccelerate { get { return _MaxAccelerate; } set { _MaxAccelerate = value; } } public Truck(string regNo, string typeOfVehicle, string make, string model, Color color, decimal price, DateTime dateofmanufacture) : base(regNo, typeOfVehicle, make, model, color, price, dateofmanufacture) { //this.Status = "Congratulations on buying a new Truck "; if ((DateTime.Now.Year - DateOfManufacture.Year) == 0) { _Status = "Congratulations on Purchasing a new Truck"; } else { _Status = "Your current price of the vehicle is:" + CurrentPrice; } } public override string ToString() { return "Your Truck is running at the Speed" + Speed + "\r\n Color:" + Color + "\r\n Make:" + Make + "\r\n Model:" + Model; } public override void Accelerate(int offsetSpeed) { if (Speed + offsetSpeed >= _MaxAccelerate) { throw new ApplicationException("Your crossing Max speed"); } else { Speed += offsetSpeed; } } public override void Start() { Speed = 20; _CurrentPrice = Price; int difference = DateTime.Now.Year - this.DateOfManufacture.Year; if (difference > Vehicle.ServiceYear) //Car.ServiceYear { throw new ApplicationException("Truck Expired"); } _Status = "Truck started at the speed of 20"; } public override void Stop() { Speed = 0; _Status = "Your truck stopped at the speed of" + Speed; } } }
Right click on the solution and add wind form and design a wind from like given below screen

Right-click on Widform go to view code and add given below code
public partial class VehicleForm : Form { public VehicleForm() { InitializeComponent(); } Vehicle objVehicle; private void btnCreate_Click(object sender, EventArgs e) { if (rbnCar.Checked) { objVehicle = new Car(txtRegNo.Text, rbnCar.Text, cmbMake.Text, cmbModel.Text, (Color)Enum.Parse(typeof(Color), cmbColor.Text), Convert.ToDecimal(txtPrice.Text), dtpdate.Value); } else if (rbnTruck.Checked) { objVehicle = new Truck(txtRegNo.Text, rbnTruck.Text, cmbMake.Text, cmbModel.Text,(Color) Enum.Parse(typeof(Color),cmbColor.Text), Convert.ToDecimal(txtPrice.Text), Convert.ToDateTime(dtpdate.Text)); } txtVehicleId.Text = objVehicle.VehicleId.ToString(); lblmsg.Text = objVehicle.Status; } private void VehicleForm_Load(object sender, EventArgs e) { cmbMake.Items.Add("Select Car Type"); cmbMake.Items.Add("Fiat-Chrysler"); cmbMake.Items.Add("Hyundai"); cmbMake.Items.Add("Maruti"); cmbMake.Items.Add("Ford Motor"); cmbMake.Items.Add("Renault-Nissan Alliance"); cmbColor.Items.Add("Select Color"); cmbColor.Items.Add("Black"); cmbColor.Items.Add("Brown"); cmbColor.Items.Add("Grey"); cmbColor.Items.Add("White"); cmbColor.Items.Add("Red"); cmbColor.SelectedIndex = 0; cmbMake.SelectedIndex = 0; cmbModel.SelectedText = "Select Model"; } private void btnget_Click(object sender, EventArgs e) { dtpdate.Text = objVehicle.DateOfManufacture.ToString(); txtRegNo.Text = objVehicle.RegNo.ToString(); cmbColor.Text = objVehicle.Color.ToString(); cmbModel.Text = objVehicle.Model; txtPrice.Text = objVehicle.Price.ToString(); cmbMake.Text = objVehicle.Make; txtSpeed.Text = objVehicle.Speed.ToString(); txtVehicleId.Text = objVehicle.VehicleId.ToString(); } private void btnClear_Click(object sender, EventArgs e) { lblStatus.Text = " "; txtRegNo.Clear(); cmbColor.Text=""; cmbModel.Text = ""; txtPrice.Clear(); cmbMake.Text = ""; txtSpeed.Clear(); txtVehicleId.Text = ""; } private void btnStart_Click(object sender, EventArgs e) { objVehicle.Start(); lblStatus.Text = objVehicle.Status; txtSpeed.Text = "20"; if ((DateTime.Now.Year - objVehicle.DateOfManufacture.Year) > Vehicle.ServiceYear) { throw new ApplicationException("Your car service year has expired"); } //lblStatus.Text = ; } private void btnStop_Click(object sender, EventArgs e) { objVehicle = null; txtSpeed.Text = null; } private void btnAccelerate_Click(object sender, EventArgs e) { if (Convert.ToInt32(txtSpeed.Text) < 20) { throw new ApplicationException("Car speed should not be less the 20"); } objVehicle.Accelerate(Convert.ToInt32(txtSpeed.Text)); lblStatus.Text = objVehicle.ToString(); } private void btnDeaccelerate_Click(object sender, EventArgs e) { objVehicle.DeAccelerate(Convert.ToInt32(txtSpeed.Text)); lblStatus.Text = objVehicle.ToString(); } private void cmbMake_SelectedIndexChanged(object sender, EventArgs e) { switch (cmbMake.SelectedItem.ToString()) { case "Fiat-Chrysler": cmbModel.Items.Clear(); cmbModel.Items.Add("Alfa Romeo"); cmbModel.Items.Add("Fiat"); cmbModel.Items.Add("Jeep"); break; case "Hyundai": cmbModel.Items.Clear(); cmbModel.Items.Add("Hyundai Eon"); cmbModel.Items.Add("Hyundai i10"); cmbModel.Items.Add("Hyundai Xcent"); break; case "Maruti": cmbModel.Items.Clear(); cmbModel.Items.Add("Maruti Suzuki Alto 800"); cmbModel.Items.Add("Maruti Suzuki Omni"); cmbModel.Items.Add("Maruti Suzuki Ritz"); break; case "Ford Motor": cmbModel.Items.Clear(); cmbModel.Items.Add("Ford Ecosport"); cmbModel.Items.Add("Ford Figo Aspire"); break; case "Renault-Nissan Alliance": cmbModel.Items.Clear(); cmbModel.Items.Add("Renault Duster"); cmbModel.Items.Add("Renault Sandero"); break; } } }
Run the application and go through implemented code
Inheritance in c# with real time example Description
Vehicle(Parent class):
Instance Fieldmembers:
- public-NoOfTyres- no of tires
- private-Accessories-check if accessories present or not
- protected-Brand- Brand of the car.
Static FieldMember: private- Counter-No of Vehicle objects created
Constructor: Parameterless Constructor: Increment Counter. Parameterized Constructor with parameters as noOfTyres, accessories, and brand.
Instance Methods: IsPresent()-Print message with the Number of Vehicle objects created. GetBrand()-Print message with the Brand name of the vehicle.
StaticMethod: GetNoOfVehicles().
Car(Child class):
Constructor: Parameterized Constructor with parameters as noOfTyres, accessories, brand and car number also call the base class constructor.
Instance Field Member: CarNumber with private access modifier.
Instance Method: PrintCarInfo().
Main: Create Car Instance and initialize values to the field members.
Calling PrintCarInfo() Method.
- How to create dynamic form fields using jQuery - January 4, 2021
- What is CTS (Common Type System) in .Net - October 16, 2020
- What is main method in c# - October 13, 2020
Saved as a favorite!, I love it!
First time visiting your website, I really like your website!
tҺe website іѕ really good, I enjoy your website!
Bookmarked!, I like your blog!