A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

C# Tutorial 7.4: Abstraction

 Abstraction is an important concept in object-oriented programming (OOP) and is one of the key principles of OOP. In C#, abstraction is achieved through abstract classes and interfaces. This tutorial will guide you through the basics of abstraction in C#.

Abstraction in C#

1. Abstract Classes:

An abstract class is a class that cannot be instantiated and is typically used as a base class for other classes. It may contain abstract and non-abstract (concrete) methods. Abstract methods have no implementation in the abstract class and must be implemented by derived classes.

// Example of an abstract class
abstract class Shape
{
    public abstract void Draw(); // Abstract method with no implementation
    public void Display()
    {
        Console.WriteLine("Displaying shape");
    }
}

// Derived class implementing the abstract method
class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a circle");
    }
}

2. Interfaces:

An interface is a contract that defines a set of methods and properties that a class must implement. Unlike abstract classes, interfaces can be implemented by multiple classes, providing a way to achieve multiple inheritances in C#.

// Example of an interface
interface IDrawable
{
    void Draw();
}

// Class implementing the interface
class Square : IDrawable
{
    public void Draw()
    {
        Console.WriteLine("Drawing a square");
    }
}

3. Using Abstraction in Code:

Now, let's use the abstract class and interface in a program:

class Program
{
    static void Main()
    {
        // Using abstract class
        Shape circle = new Circle();
        circle.Draw();    // Calls the overridden method in Circle
        circle.Display(); // Calls the method in the abstract class

        // Using interface
        IDrawable square = new Square();
        square.Draw();    // Calls the method in Square
    }
}

Summary:

  • Abstraction helps in hiding the complex implementation details and exposing only the necessary functionalities.
  • Abstract classes and interfaces provide a way to achieve abstraction in C#.
  • Abstract classes can have a mix of abstract and concrete methods, while interfaces only contain method and property declarations.
  • Abstract classes are used for common functionality among derived classes, and interfaces define a contract that multiple classes can implement.