In this article, we will discuss what is encapsulation and encapsulation in c# with real time example by using windows Applications
What is Encapsulation in C#
The warping of data and member functions into the single unit then it called as Encapsulation this data is available at the class level( object within a secured and controlled environment ) and by using Data Hiding we will achieve the Encapsulation in C#
In the class level, we have a Binding of data and behavior i.e. functionality of an object within a secured and controlled environment is also called encapsulation in c#.
Advantages of Encapsulation in C#
✔️ Data Hiding / Abstraction. ✔️Implementation Abstraction ✔️It makes the class simpler to use. ✔️ Loose Coupling
Encapsulation in c# with Example
Go to visual studio ⭢ select windows application ⭢ Name: vechileEncapsulation

Right Click on Solution ⭢ Add ⭢ Class name as Vehicle

Read the given below case study carefully and Build a class called Car Create Car class – Encapsulation
Instance members
- VehicleId – This should be auto-incremented for each object.
- Registration number: Is of type string.
- DateOfManufacture – Is of Type DateTime
- Color – Is of type Enum and should be valued from White, Black, Red, Grey, Brown
- Make – Is of type string
- Model – Is of type string
- Price – Is of type Decimal.
- current price – Readonly decimal property and should return value depreciated at 10% per annum. If the actual price is 100 after One year its CurrentPrice would be 90(100-10%) and after two
years it would be 81 (90-10%) and so on - Status – A read-only string that shows the current speed of the car.
Instance Constructor:
- Provide constructor with Parameters to initialize all the Instance Members
- Set Status to “Congratulations on Purchasing a new car”
Static Members:
- MaxAccelarateSpeed – When we accelerate the car we cannot increase speed by this amount.
- MinDecelarateSpeed – When we decelerate the car, we cannot decrease speed by this amount.
- ServiceYears: After these many years, Car cannot Start and will throw an error – “Car Expired”
Instance Methods:
- Start() method
- Set the car to an initial speed of 20.
- After Service Years, Car should throw an exception with the message “Car Expired” and not start.
- Change the Status eg. “Car Started at a speed of 20”
- Stop() method
- Set the car speed to 0
- Set the Status eg: “Car Stopped”
- Accelerate(int offsetSpeed):
- To increase the Speed of Car by offset speed .
- offset speed should not be greater than MaxAccerateSpeed.
- Car Speed should not go beyond 140
- Decelerate(int offset speed)
- To decrease the Speed of Car by speed offset.
- offset speed should not be less than MinDecelarateSpeed.
- Car Speed cannot be less than 0.
Add the given below code in your vehicle class this vehicle class can have car class and Enum For colors
public enum Colorss
{
White = 0,
Black,
Red,
Grey,
Brown
}
public class Car
{
public Colorss color;
private string _RegNo;
public string RegNo
{
set
{
_RegNo = value;
}
get
{
return _RegNo;
}
}
public static int _PrevId; //Static members are shared by all objects of a class
private int _VehicleId;
public int VehicleId
{
get
{
return _VehicleId;
}
}
public string Model;
public double Price;
public int Speed;
private DateTime _DateOfManufacture; // Date of manufacture should not be more than 15 years
public DateTime DateOfManufacture
{
get
{
return _DateOfManufacture;
}
set
{
_DateOfManufacture = value;
}
}
public string Make;
public override string ToString() // Overridden ToString() to display current status of car
{
string str = "";
return str += "Your Car is running at the Speed" + Speed + "\r\n Color:" + color + "\r\n Make:" + Make + "\r\n Model:" + Model;
}
public Car()
{
_PrevId++;
_VehicleId = _PrevId;
}
public Car(string regNo, Colorss color, string model, string make, double price, DateTime dateofmanufacture)
: this() //Calls default constructor of same class for initializing _Id
{
RegNo = regNo;
this.color = color;
Model = model;
Make = make;
Price = price;
DateOfManufacture = dateofmanufacture;
}
public void Accelerate(int speedIncrement)
{
if (Speed + speedIncrement >= 160)
{
throw new ApplicationException("You are crossing Maxspeed");
}
else
{
Speed += speedIncrement;
}
}
public void DeAccelerate(int speedDecrement)
{
if (Speed - speedDecrement <= 10)
{
throw new ApplicationException("Your car is going to stop");
}
else
{
Speed -= speedDecrement;
}
}
}
Encapsulation in c# with real time example
Build the GUI as below and program each button using the above Car class.

Right-click on Widform go to view code and add given below code
public partial class VehicleForm : Form
{
public VehicleForm()
{
InitializeComponent();
}
Car objCar;
private void btnCreate_Click(object sender, EventArgs e)
{
objCar = new Car(txtRegNo.Text, (Colorss)Enum.Parse(typeof(Colorss), cmbColor.Text), cmbModel.Text, cmbMake.Text, Convert.ToInt32(txtPrice.Text), Convert.ToDateTime(dtpdate.Text));
int id = Convert.ToInt32(txtRegNo.Text);
txtVehicleId.Text = objCar.VehicleId.ToString();
}
private void VehicleForm_Load(object sender, EventArgs e)
{
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;
}
private void btnget_Click(object sender, EventArgs e)
{
txtVehicleId.Text = objCar.VehicleId.ToString();
dtpdate.Text = objCar.DateOfManufacture.ToString();
txtRegNo.Text = objCar.RegNo.ToString();
cmbColor.Text = objCar.color.ToString();
cmbModel.Text = objCar.Model.ToString();
txtPrice.Text = objCar.Price.ToString();
cmbMake.Text = objCar.Make;
//txtSpeed.Text = objCar.Speed.ToString();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtVehicleId.Clear();
lblStatus.Text = " ";
txtRegNo.Clear();
cmbColor.Text = "";
cmbModel.Text = "";
txtPrice.Clear();
cmbMake.Text = "";
//txtSpeed.Clear();
}
private void btnStart_Click(object sender, EventArgs e)
{
if ((DateTime.Now.Year - objCar.DateOfManufacture.Year) > 15)
{ throw new ApplicationException("Error"); }
objCar.Speed = 20;
}
private void btnStop_Click(object sender, EventArgs e)
{
objCar.Speed = 0;
//txtSpeed.Text = null;
}
private void btnAccelerate_Click(object sender, EventArgs e)
{
objCar.Accelerate(10);
//txtSpeed.Text = objCar.Speed.ToString();
lblStatus.Text = objCar.ToString();
}
private void btnDeaccelerate_Click(object sender, EventArgs e)
{
objCar.DeAccelerate(10);
txtSpeed.Text = objCar.Speed.ToString();
lblStatus.Text = objCar.ToString();
}
private void dtpdate_ValueChanged(object sender, EventArgs e)
{
//DateTime dt = Convert.ToDateTime(dtpdate.Text);
//if (dt < DateTime.Now.AddYears(-15))
//{
// throw new ApplicationException("Your Registration Number is Expired");
//}
}
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 Application
- how to create ASP.NET Core 3 Web API Project - January 21, 2022
- JWT Authentication using OAUTH - January 10, 2022
- Ado.net database Transactions - January 9, 2022
I really like how you wrote about Encapsulation in c# with real-time examples.
tҺe website іѕ really good, I love your web site!
Saved as a favorite!, I love your blog!
Saved as a favorite!, I like it!
tҺe website іѕ really good, I enjoy it!
great article. Your knowledge is utterly intensive. I enjoyed reading the article on your Website
tҺe website іѕ really good, I enjoy your website!
Bookmarked!, I love your site!