C# is an object-oriented language that helps organize code using real-world concepts like objects, classes, inheritance, and more. OOP makes code reusable, scalable, and easier to maintain.
A class is a blueprint. An object is an instance of that class.
class Car
{
public string brand = "Ford";
public void Honk()
{
Console.WriteLine("Beep beep!");
}
}
class Program
{
static void Main()
{
Car myCar = new Car(); // Object
myCar.Honk(); // Method call
Console.WriteLine(myCar.brand);
}
}
Encapsulation hides internal object details and only shows whatβs necessary. This is achieved using private
fields and public
methods.
class Student
{
private string name;
public void SetName(string newName)
{
name = newName;
}
public string GetName()
{
return name;
}
}
Inheritance allows a class to use properties and methods of another class.
class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Barking...");
}
}
Polymorphism allows you to use the same method name in different ways.
class Animal
{
public virtual void Sound()
{
Console.WriteLine("Animal sound");
}
}
class Cat : Animal
{
public override void Sound()
{
Console.WriteLine("Meow");
}
}
Abstraction hides complexity using abstract classes or interfaces.
abstract class Shape
{
public abstract void Draw();
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing Circle");
}
}
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!