In C#, Object-Oriented Programming (OOP) is based on four main pillars: Encapsulation, Abstraction, Inheritance, and Polymorphism. Here’s a brief overview of each pillar:
-
Encapsulation
Encapsulation involves bundling the data (attributes) and methods (functions) that operate on that data into a single unit called a class. It also restricts direct access to some of the object's components, which can prevent the accidental modification of data. In C#, you typically use access modifiers (likeprivate
,protected
, andpublic
) to enforce encapsulation.Example:
public class BankAccount
{
private decimal balance;
public void Deposit(decimal amount)
{
if (amount > 0) balance += amount;
}
public decimal GetBalance()
{
return balance;
}
} -
Abstraction
Abstraction allows you to hide complex implementation details and expose only the necessary features of an object. This helps in reducing complexity and increasing efficiency. In C#, abstraction can be achieved using abstract classes and interfaces.Example:
public abstract class Shape
{
public abstract double Area();
}
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public override double Area()
{
return Width * Height;
}
} -
Inheritance
Inheritance allows a class to inherit the attributes and methods of another class. This promotes code reusability and establishes a relationship between classes. In C#, you can derive a class from a base class using the:
syntax.Example:
public class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Barking...");
}
}
Dog myDog = new Dog();
myDog.Eat();
// Inherited method myDog.Bark();
// Dog-specific method -
Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon, even if they share the same name. There are two types: compile-time (method overloading) and runtime (method overriding).Example (Method Overriding):
public class Animal
{
public virtual void Speak()
{ Console.WriteLine("Animal speaks");
}
}
public class Cat : Animal
{
public override void Speak()
{
Console.WriteLine("Cat meows");
}
}
Animal myCat = new Cat();
myCat.Speak();
// Outputs: Cat meows
Summary
These four pillars—Encapsulation, Abstraction, Inheritance, and Polymorphism—are fundamental to OOP in C#. They help in designing robust, maintainable, and reusable software.