What is Object-Oriented Programming (OOP) in C#?
Object-Oriented Programming (OOP) in C# is a fundamental programming paradigm that revolves around the concept of organizing code into objects, each encapsulating both data and the functions that operate on that data. In C#, classes serve as blueprints for creating these objects, defining their structure (attributes or properties) and behavior (methods or functions).
This approach mimics real-world entities, making it easier to model complex systems and interactions. Encapsulation ensures that the internal workings of an object are hidden from the outside, promoting security and modularity. Inheritance allows classes to inherit attributes and behaviors from other classes, fostering code reuse and hierarchical relationships. Polymorphism enables objects to be treated as instances of their base class, facilitating dynamic behavior. By abstracting complex systems into manageable classes and leveraging concepts like interfaces, constructors, and access modifiers, developers can create efficient, modular, and scalable applications in C# that align closely with real-world scenarios.
Four Pillars of Object-Oriented Programming (OOP)
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
Let's start with class and object.
What is a Class?
- A class is a blueprint or template for creating objects.
- It defines the structure and behavior of objects that belong to that class. A class encapsulates data (attributes) and methods (functions) that operate on that data.
- It serves as a model for creating instances, which are individual objects that follow the characteristics and behaviors defined by the class.
using System;
// Define a class named "Car"
class Car
{
// Attributes/Fields
public string Make;
public string Model;
public string Color;
public int Year;
// Constructor
public Car(string make, string model, string color, int year)
{
Make = make;
Model = model;
Color = color;
Year = year;
}
// Method
public void StartEngine()
{
Console.WriteLine("Engine started for the " + Make + " " + Model);
}
}
class Program
{
static void Main(string[] args)
{
// Create instances of the Car class
Car car1 = new Car("Toyota", "Camry", "Blue", 2022);
Car car2 = new Car("Ford", "Mustang", "Red", 2023);
// Access attributes and methods of the instances
Console.WriteLine("Car 1: " + car1.Make + " " + car1.Model + ", " + car1.Color + ", " + car1.Year);
car1.StartEngine();
Console.WriteLine("Car 2: " + car2.Make + " " + car2.Model + ", " + car2.Color + ", " + car2.Year);
car2.StartEngine();
}
}
Car class is defined with attributes (Make, Model, Color, Year), a constructor that initializes these attributes, and a method (StartEngine) that prints a message indicating the engine has started. The Main method in the Program class demonstrates how to create instances of the Car class and interact with their attributes and methods.
Object
- The object is an instance of a class. A class defines a blueprint that describes the structure and behavior of objects, while an object is a concrete entity created based on that blueprint.
- In other words, a class is like a template or a blueprint, and an object is a specific realization of that template with its own unique data and state.
- An object has attributes (also called properties, fields, or member variables) that store data, and it can have methods (also called member functions) that define its behavior. When you create an object from a class, you're essentially creating a specific instance of that class with its own set of attribute values.
For example, if you have a Car class, an object of that class could represent a specific car with its make, model, color, and other attributes. The methods of the class might allow you to perform actions on the car, like starting the engine or driving.
Car car1 = new Car("Toyota", "Camry", "Blue", 2022); // Creating an object of the Car class
car1.StartEngine(); // Calling the StartEngine method on the car1 object
Car car2 = new Car("Ford", "Mustang", "Red", 2023); // Creating another object of the Car class
car2.StartEngine(); // Calling the StartEngine method on the car2 object
car1 and car2 are objects of the Car class. They are distinct instances of the class, each with its own set of attribute values. The StartEngine method is called on each object to perform the specified action for each car individually.
Encapsulation
Encapsulation in C# is a fundamental concept in object-oriented programming that involves bundling data (attributes) and methods (functions) that operate on that data into a single unit, known as a class. The idea is to hide the internal details of an object and provide controlled access to its properties and behaviors.
A real-world example of encapsulation can be understood using the analogy of a television:
Imagine you have a television at home. The television has various buttons and settings, but you don't need to understand the intricate details of how it works internally to operate it. The manufacturer has encapsulated the complex electronics and components inside a casing, providing you with a remote control and a user interface (the buttons) to interact with the TV.
In C#, encapsulation is achieved by defining classes with private fields (attributes) and public methods (behaviors) to interact with those fields. The private fields are not directly accessible from outside the class, ensuring that the internal state is protected. Public methods provide controlled access to the internal data, allowing users of the class to interact with it in a well-defined manner.
public class Television
{
private bool isOn;
private int currentChannel;
public Television()
{
isOn = false;
currentChannel = 1;
}
public void TurnOn()
{
isOn = true;
Console.WriteLine("TV is now on.");
}
public void TurnOff()
{
isOn = false;
Console.WriteLine("TV is now off.");
}
public void ChangeChannel(int channel)
{
if (isOn)
{
currentChannel = channel;
Console.WriteLine("Changed to channel: " + channel);
}
else
{
Console.WriteLine("TV is off. Cannot change channel.");
}
}
}
Television the class encapsulates the internal state (whether it's on or off, the current channel) and provides methods to interact with it (turning on/off, changing channels). The user of the class can only interact with the TV through these defined methods.
Inheritance
To create a new class (called the subclass or derived class) based on an existing class (called the superclass or base class). The subclass inherits attributes and methods from the superclass, and it can also add its own unique attributes and methods or override existing ones. Inheritance promotes code reuse and helps in organizing classes in a hierarchy.
For example, Imagine you have a base class called Animal that defines common attributes and behaviors for all animals. Then, you can create specific animal types (subclasses) that inherit from the Animal class and add their own specialized attributes and behaviors.
-
Base Class (Superclass) - Animal: This class defines attributes common to all animals, like
nameandage, and methods common to all animals, likeEat()andSleep(). -
Subclasses (Derived Classes) - Dog and Cat: These classes inherit from the
Animalclass. They automatically have attributes and methods from the base class. Additionally, they can have their own unique attributes (e.g.,breedfor dogs) and behaviors (e.g.,Bark()for dogs andMeow()for cats).

Join the conversation! Your thoughts help the community grow.