OOP Concepts in C#

Object-Oriented Programming (OOP) is a programming approach that organizes code using objects and classes. C# is a fully object-oriented language.

OOP helps in building reusable, scalable, and easy-to-maintain applications.

Main OOP Concepts

  • Class
  • Object
  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

1. Class

A class is a blueprint used to create objects. It defines properties (data) and methods (behavior).


class Person
{
    public string Name;
    public int Age;

    public void Show()
    {
        Console.WriteLine(Name + " " + Age);
    }
}
    

2. Object

An object is an instance of a class.


Person p1 = new Person();
p1.Name = "Rahul";
p1.Age = 25;
p1.Show();
    

3. Encapsulation

Encapsulation means wrapping data and methods together and restricting direct access using access modifiers.


class Student
{
    private int marks;

    public void SetMarks(int m)
    {
        marks = m;
    }

    public int GetMarks()
    {
        return marks;
    }
}
    

4. Inheritance

Inheritance allows a class to acquire properties and methods of another class using :.


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

class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Barking...");
    }
}
    

5. Polymorphism

Polymorphism means "many forms". It allows methods to behave differently based on the object.


class Shape
{
    public virtual void Draw()
    {
        Console.WriteLine("Drawing shape");
    }
}

class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing circle");
    }
}
    

6. Abstraction

Abstraction hides implementation details and shows only essential features using abstract classes or interfaces.


abstract class Vehicle
{
    public abstract void Start();
}

class Car : Vehicle
{
    public override void Start()
    {
        Console.WriteLine("Car started");
    }
}
    

Key Points

  • OOP improves code reusability
  • Encapsulation provides data security
  • Inheritance supports code reuse
  • Polymorphism increases flexibility
  • Abstraction reduces complexity

Conclusion

OOP concepts form the backbone of C# programming. Understanding these concepts is essential for developing real-world applications.

C# OOP Quiz

Q1. Which concept hides data?



Q2. Which keyword is used for inheritance?



Q3. Which keyword is used to override a method?


C# Introduction C# Variables & Keywords C# Data Types C# If Else Statement C# Loops C# Comments C# Type Casting C# User Input C# Operators C# Math C# String C# OOP Concepts C# Classes and Objects C# Multiple Classes and Objects C# Class Members C# Constructors C# Access Modifiers