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.
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);
}
}
An object is an instance of a class.
Person p1 = new Person();
p1.Name = "Rahul";
p1.Age = 25;
p1.Show();
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;
}
}
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...");
}
}
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");
}
}
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");
}
}
OOP concepts form the backbone of C# programming. Understanding these concepts is essential for developing real-world applications.