C# Programming Tutorial: From Fundamentals to Advanced Application Development

5.22K 0 0 0 0

📘 Chapter 4: Object-Oriented Programming in C#

🧠 Introduction

C# is fundamentally an object-oriented programming (OOP) language. OOP is a paradigm that organizes software design around objects, rather than functions and logic. These objects represent real-world entities with attributes (properties) and behaviors (methods).

OOP helps in code reuse, abstraction, modularity, scalability, and maintainability. This chapter explores all the major principles of OOP in C# and how to implement them.


🎯 Four Pillars of OOP in C#

Principle

Description

Encapsulation

Hiding internal state using access modifiers

Abstraction

Exposing only essential features to the user

Inheritance

Reusing code by creating a child-parent relationship

Polymorphism

Objects behaving differently in different contexts


🔧 1. Classes and Objects

🔹 What is a Class?

A class is a blueprint for creating objects. It defines fields, properties, methods, and constructors.

class Car

{

    public string Brand;

    public void Honk()

    {

        Console.WriteLine("Beep!");

    }

}


🔹 What is an Object?

An object is an instance of a class.

Car myCar = new Car();

myCar.Brand = "Toyota";

myCar.Honk();  // Output: Beep!


📋 Class vs Object

Concept

Description

Example

Class

Blueprint/template

Car

Object

Instance of the class

new Car()


📦 2. Encapsulation

Encapsulation refers to wrapping data (fields) and code (methods) into a single unit (class) and restricting access using access modifiers.


🔹 Access Modifiers

Modifier

Access Scope

public

Accessible from anywhere

private

Accessible only within the class

protected

Accessible in class and subclasses

internal

Accessible within the same assembly

protected internal

Accessible within assembly and subclass


Example:

class Person

{

    private int age;

 

    public void SetAge(int value)

    {

        if (value > 0) age = value;

    }

 

    public int GetAge()

    {

        return age;

    }

}


🧱 3. Constructors and Destructors


🔹 Constructor

A constructor is a special method that runs automatically when an object is created.

class Student

{

    public string Name;

 

    public Student(string name)

    {

        Name = name;

    }

}


🔹 Default Constructor

public Student()

{

    Name = "Unknown";

}


🔹 Destructor

~Student()

{

    // Cleanup code

}

Destructors are rarely used directly and are called by the garbage collector.


🧱 4. Inheritance

Inheritance allows one class (child/derived) to inherit fields and methods from another (parent/base).

class Animal

{

    public void Eat() { Console.WriteLine("Eating..."); }

}

 

class Dog : Animal

{

    public void Bark() { Console.WriteLine("Barking..."); }

}

Usage

Dog d = new Dog();

d.Eat();   // inherited

d.Bark();  // own method


📋 Inheritance Types in C#

Type

Description

Single

One class inherits from one class

Multi-level

A → B → C

Hierarchical

One base, many derived

Multiple

Not directly supported (use interfaces)


🧠 5. Polymorphism

Polymorphism means many forms—the same method behaves differently depending on the object.


🔹 Compile-Time (Method Overloading)

class Calculator

{

    public int Add(int a, int b) => a + b;

    public float Add(float a, float b) => a + b;

}


🔹 Run-Time (Method Overriding)

class Animal

{

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

}

 

class Dog : Animal

{

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

}

Animal a = new Dog();

a.Speak();  // Output: Bark


📋 Table: Overloading vs Overriding

Feature

Overloading

Overriding

Compile-time

Yes

No

Runtime

No

Yes

Signature Change

Yes

No (same method signature)

Keyword

None

virtual and override


🔗 6. Abstraction

Abstraction is hiding complex implementation and showing only relevant information.

Implemented via:

  • Abstract classes
  • Interfaces

🔹 Abstract Class

abstract class Shape

{

    public abstract void Draw();

}

 

class Circle : Shape

{

    public override void Draw()

    {

        Console.WriteLine("Drawing Circle");

    }

}


🔹 Interface

An interface is a pure abstraction—no implementation.

interface IDriveable

{

    void Drive();

}

 

class Car : IDriveable

{

    public void Drive()

    {

        Console.WriteLine("Driving...");

    }

}


📋 Abstract Class vs Interface

Feature

Abstract Class

Interface

Methods

Can have both abstract & concrete

All methods are abstract

Fields

Yes

No

Inheritance

One per class

Multiple interfaces allowed

Use When

Sharing base functionality

Ensuring common behavior


🔄 7. Properties in C#

Properties wrap fields with get and set accessors.

class Product

{

    private int price;

 

    public int Price

    {

        get { return price; }

        set { if (value > 0) price = value; }

    }

}

Or, use auto-implemented properties:

public string Name { get; set; }


🧪 Sample Program: OOP Principles in Action

using System;

 

abstract class Animal

{

    public abstract void MakeSound();

}

 

class Dog : Animal

{

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

}

 

class Program

{

    static void Main()

    {

        Animal myDog = new Dog();

        myDog.MakeSound();  // Output: Bark

    }

}


Summary Table


Concept

Key Idea

Example

Class

Template for objects

class Car {}

Object

Instance of class

Car c = new Car();

Encapsulation

Hide data via access modifiers

private, public

Abstraction

Show relevant details only

abstract class, interface

Inheritance

Child class inherits base class

class Dog : Animal

Polymorphism

One interface, many behaviors

override, virtual

Back

FAQs


1. Q: Is C# easy to learn for beginners?

A: Yes, especially with Visual Studio and .NET’s extensive documentation and community support.

2. Q: Do I need to know C or C++ before learning C#?

A: Not at all. C# is independent and designed for new learners.

3. Q: Can I build web apps using C#?

A: Yes, using ASP.NET Core you can build scalable web apps and APIs.

4. Q: What’s the difference between C# and Java?

A: Both are similar syntactically, but C# is part of the Microsoft .NET ecosystem and often integrates better with Windows technologies.

5. Q: Is C# only for Windows development?

A: Not anymore. With .NET Core and .NET 8, C# is cross-platform.

6. Q: Is C# good for game development?

A: Absolutely. It is the main language used in Unity.

7. Q: Which IDE is best for C#?

A: Visual Studio is the most powerful and popular IDE for C# development.

8. Q: Can I use C# for mobile development?

 A: Yes, with Xamarin or .NET MAUI, C# can build cross-platform mobile apps.

9. Q: What is the future of C# in 2025 and beyond?

A: C# continues to evolve with modern features and has strong backing from Microsoft, making it future-proof.

10. Q: Do I need internet to use C# tools?

A: No, you can code, compile, and run C# locally, though some online libraries/tools may require internet.