CHASH Tutorial



C# ABSTRACTION


C# Abstraction

Abstraction in C# is the concept of hiding complex implementation details and showing only the essential features of an object. It helps reduce programming complexity and effort.

🧠 Key Benefit: Abstraction lets you focus on "what" an object does, instead of "how" it does it.

How to Achieve Abstraction in C#?

  • Abstract Classes
  • Interfaces

1. Using Abstract Classes

An abstract class cannot be instantiated. It can contain abstract methods (no body) and non-abstract methods (with body).

abstract class Animal
{
    public abstract void MakeSound();  // Abstract method

    public void Sleep()                // Regular method
    {
        Console.WriteLine("Sleeping...");
    }
}

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

class Program
{
    static void Main()
    {
        Dog d = new Dog();
        d.MakeSound();  // Output: Bark!
        d.Sleep();      // Output: Sleeping...
    }
}
  
βœ… Output:
Bark!
Sleeping...

2. Using Interfaces

An interface is like a contract. It defines methods without implementing them. A class that implements the interface must define all its members.

interface IShape
{
    void Draw();
}

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

class Program
{
    static void Main()
    {
        IShape shape = new Circle();
        shape.Draw();  // Output: Drawing Circle
    }
}
  
🎯 Interfaces allow multiple inheritance and full abstraction.

Real-World Analogy

πŸ”’ Think of an ATM machine. You interact with buttons (interface) and screen (abstracted features), but you don't see the internal logic, code, or mechanisms.

Why Use Abstraction?

  • Reduces code complexity
  • Improves security by exposing only necessary features
  • Helps in implementing real-world systems efficiently
  • Promotes code reusability
πŸ“ Note:
You can’t create an object of an abstract class or interface, but you can use them as references.

🌟 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