C# Object-Oriented Programming
Understanding OOP concepts in C#
🎯 What is OOP?
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects containing data and methods. It makes code reusable, organized, and easier to maintain through key principles.
// Simple OOP example
class Dog
{
public string Name;
public void Bark()
{
Console.WriteLine("Woof!");
}
}
Four Pillars of OOP
Encapsulation
Bundling data and methods together, hiding internal details from outside access.
class BankAccount
{
private decimal balance;
public void Deposit(decimal amount)
{
balance += amount;
}
}
Inheritance
Creating new classes from existing ones, inheriting properties and methods for code reuse.
class Animal { }
class Dog : Animal
{
// Inherits from Animal
}
Polymorphism
Objects taking many forms, allowing methods to behave differently based on the object type.
class Animal
{
public virtual void Sound()
{
Console.WriteLine("Some sound");
}
}
Abstraction
Hiding complex implementation details and showing only essential features to users.
abstract class Shape
{
public abstract double Area();
}
🔹 Encapsulation Example
Encapsulation in C# is achieved by defining private fields and exposing them through public properties or methods. This principle protects an object's internal state from direct external modification, ensuring data integrity and controlled access. By using getters and setters, you can add validation, logging, or business logic. Encapsulation is a core pillar of object-oriented programming that promotes secure, maintainable, and robust code design.
class Student
{
private string name;
private int age;
public void SetName(string studentName)
{
name = studentName;
}
public string GetName()
{
return name;
}
public void SetAge(int studentAge)
{
if (studentAge > 0)
age = studentAge;
}
}
// Usage
Student student = new Student();
student.SetName("John");
student.SetAge(20);
Output:
Student name is protected and can only be set through SetName() method.
🔹 Inheritance Example
Inheritance enables a derived class to acquire properties and methods from a base class, fostering code reuse. In C#, you use the colon (:) syntax to establish an inheritance relationship. This allows you to create specialized classes that extend or modify base behavior. Inheritance supports the "is-a" relationship, simplifying hierarchical data modeling and reducing redundancy, which is fundamental in building scalable and organized object-oriented systems.
// Base class
class Vehicle
{
public string Brand = "Ford";
public void Honk()
{
Console.WriteLine("Beep beep!");
}
}
// Derived class
class Car : Vehicle
{
public string Model = "Mustang";
}
// Usage
Car myCar = new Car();
myCar.Honk(); // Inherited method
Console.WriteLine(myCar.Brand + " " + myCar.Model);
Output:
Beep beep!
Ford Mustang
🔹 Polymorphism Example
Polymorphism allows methods to take multiple forms, enabling derived classes to provide specific implementations of base class methods. In C#, this is achieved using the virtual keyword in the base method and override in derived classes. Runtime polymorphism ensures the correct method is called based on the object's actual type, enhancing flexibility and enabling dynamic behavior in applications like plugin architectures or UI controls.
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("The dog barks: Woof!");
}
}
class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("The cat meows: Meow!");
}
}
// Usage
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();
myAnimal.MakeSound();
myDog.MakeSound();
myCat.MakeSound();
Output:
The animal makes a sound
The dog barks: Woof!
The cat meows: Meow!
🔹 Abstraction Example
Abstraction hides complex implementation details by exposing only essential features through abstract classes or interfaces. Abstract classes cannot be instantiated and often define abstract methods that derived classes must implement. This concept allows you to focus on what an object does rather than how it does it, simplifying interaction and promoting a clean separation of concerns in large-scale software design.
abstract class Shape
{
public abstract double GetArea();
public void Display()
{
Console.WriteLine("Area: " + GetArea());
}
}
class Circle : Shape
{
public double Radius = 5;
public override double GetArea()
{
return 3.14 * Radius * Radius;
}
}
class Rectangle : Shape
{
public double Width = 4;
public double Height = 6;
public override double GetArea()
{
return Width * Height;
}
}
// Usage
Circle circle = new Circle();
circle.Display();
Rectangle rectangle = new Rectangle();
rectangle.Display();
Output:
Area: 78.5
Area: 24
🔹 Benefits of OOP
- Reusability: Code can be reused through inheritance
- Modularity: Programs are divided into objects
- Maintainability: Easier to update and fix code
- Security: Data hiding through encapsulation
- Flexibility: Polymorphism allows flexible code