C# OOP Essentials: Concepts, Examples, and Benefits

1. Class

class is a blueprint for creating objects that encapsulate both data and behavior.

  • Access Modifiers: public, internal, abstract, sealed control visibility and inheritance.
  • Static Classes: Cannot be instantiated, contain only static members.
  • Partial Classes: Split across files using partial keyword for better organization.

Example

public class Car

{

    public string Model;

 

    public void Drive() => Console.WriteLine($"{Model} is driving.");

}

Analogy

car blueprint used to build many actual cars.

Benefits

  • Reusability
  • Encapsulation of data and logic
  • Supports abstraction and inheritance

 

2. Object

An object is an instance of a class. Managed by Garbage Collector for automatic memory cleanup. Boxing/Unboxing allows value types to be treated as objects (with some performance cost).

Example

Car car1 = new Car { Model = "Toyota" };

car1.Drive();  // Output: Toyota is driving.

Analogy

A specific Toyota car built from the Car blueprint.

Benefits

  • Enables real-world use of classes
  • Memory allocated at runtime
  • Enables interaction between data and methods

 

3. Encapsulation

Encapsulation binds data and methods into a single unit and restricts direct access. Use properties with getters/setters instead of public fields. Fine-grained access control with accessors.

Example

public class BankAccount

{

    private double balance = 1000;

 

    public void Deposit(double amount) => balance += amount;

    public double GetBalance() => balance;

}

Analogy

ATM machine—deposit or withdraw money but can't access internals.

Benefits

  • Protects data integrity
  • Controlled access
  • Simplifies system complexity

 

4. Abstraction

Abstraction hides complex internal implementation, exposing only necessary features. Interfaces provide pure abstraction. Abstract classes can include implementations. Encourages loose coupling.

Example

public abstract class Shape

{

    public abstract double GetArea();

}

Analogy

Driving a car without needing to understand how the engine works.

Benefits

  • Simplifies complex systems
  • Focus on what an object does
  • Improves modularity and readability

 

5. Inheritance

A class can inherit fields and methods from another class. Use sealed to prevent inheritance. Single inheritance for classes; multiple inheritance allowed via interfaces.

Example

public class Vehicle

{

    public void Start() => Console.WriteLine("Vehicle started");

}

 

public class Bike : Vehicle

{

    public void Ride() => Console.WriteLine("Bike is riding");

}

Analogy

A child inherits traits from their parents.

Benefits

  • Code reuse
  • Hierarchical classification
  • Simplifies extensions

 

6. Polymorphism

The same method behaves differently depending on the object. virtual, override, and new control overriding vs hiding. Interfaces enable polymorphism via multiple implementations. Compile-time (overloading) vs run-time (overriding).

Example

public class Animal

{

    public virtual void Speak() => Console.WriteLine("Animal sound");

}

 

public class Dog : Animal

{

    public override void Speak() => Console.WriteLine("Bark");

}

Analogy

A universal remote controls different devices in unique ways.

Benefits

  • Flexibility
  • Simplifies interface-based design
  • Scalability

 

7. Inheritance vs Composition

  • Inheritance: “is-a” relationship
  • Composition: “has-a” relationship
  • Favor composition for better flexibility and adherence to SRP (Single Responsibility Principle).

Composition Example

public class Engine

{

    public void Start() => Console.WriteLine("Engine started");

}

 

public class Car

{

    private Engine engine = new Engine();

    public void StartCar() => engine.Start();

}

Analogy

A car has an engine (composition); a sports car is a type of car (inheritance).

Benefits

  • Better flexibility
  • Reuse via delegation
  • Avoids tight coupling

 

8. Constructor and Destructor

  • Constructor: Initializes a new object.
  • Destructor: Cleanup before object destruction.
  • Prefer IDisposable for unmanaged resource cleanup.

Example

public class Person

{

    public string Name;

 

    public Person(string name) => Name = name;

 

    ~Person() => Console.WriteLine("Destructor called");

}

Analogy

Setting up a new apartment (constructor), cleaning it when leaving (destructor).

Benefits

  • Proper object setup
  • Helps cleanup resources

 

9. Interface and Abstract Class

Interface

  • Declares methods/properties without implementation.
  • Supports multiple inheritance.

Abstract Class

  • Can provide abstract and concrete members.
  • Can have fields.

Interface Example

public interface IAnimal

{

    void Eat();

}

 

public class Cow : IAnimal

{

    public void Eat() => Console.WriteLine("Cow eats grass");

}

Abstract Class Example

public abstract class Animal

{

    public abstract void Eat();

}

Analogy

  • Interface: A contract to fulfill.
  • Abstract class: A partially built system to extend.

Benefits

  • Extensibility
  • Code maintainability

 

10. Field vs Property vs Const vs Readonly

Concept

Modifiable

When Set

Scope

Field

Yes

Any time

Instance/static

Property

Controlled (get/set)

Via get/set

Instance/static

const

No

Compile time only

Static by default

readonly

No

Declaration or constructor

Instance/static

Example

public class Server

{

    public const double Pi = 3.14159;           // constant

    public readonly string HostName;            // readonly

 

    public Server(string hostName)

    {

        HostName = hostName;

    }

 

    private string _name;

    public string Name                           // property

    {

        get => _name;

        set => _name = value;

    }

}

 

11. Indexers

Allows accessing class data with array-like syntax.

class SampleCollection

{

    private string[] data = new string[100];

 

    public string this[int index]

    {

        get => data[index];

        set => data[index] = value;

    }

}

 

// Usage:

var collection = new SampleCollection();

collection[0] = "Hello";

Console.WriteLine(collection[0]); // Outputs "Hello"

 

 

 

Comments

Popular posts from this blog

Promises in Angular

Mastering Your Angular Workflow: Essential CLI Commands for Efficient Development

Observables in Angular