CHASH Tutorial



C# OOP


Object-Oriented Programming (OOP) in C#

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.

1. Class and Object

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);
    }
}

  

2. Encapsulation

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;
    }
}

  

3. Inheritance

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...");
    }
}

  

4. Polymorphism

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");
    }
}

  

5. Abstraction

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");
    }
}

  
Summary:
  • Class = blueprint; Object = instance of class
  • Encapsulation = hiding data
  • Inheritance = acquiring properties from another class
  • Polymorphism = same method, different behavior
  • Abstraction = hide internal details

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review