Abstract Class and Abstract Methods in CSharp

Abstract classes and methods are fundamental concepts in C# that help create structured and modular code. This article explores their use with detailed explanations and practical code examples.

1. Creating an Abstract Class

public abstract class Vehicle
{
    public string Manufacturer { get; set; }
    public abstract void Start();
    public abstract void Stop();
    public void Honk()
    {
        Console.WriteLine("Honk honk!");
    }
}

2. Implementing an Abstract Class

public class Car : Vehicle
{
    public override void Start()
    {
        Console.WriteLine("Car started");
    }

    public override void Stop()
    {
        Console.WriteLine("Car stopped");
    }
}

3. Abstract Methods

public abstract class Shape
{
    public abstract double CalculateArea();
}

4. Using Abstract Methods

public class Circle : Shape
{
    public double Radius { get; set; }

    public Circle(double radius)
    {
        Radius = radius;
    }

    public override double CalculateArea()
    {
        return Math.PI * Math.Pow(Radius, 2);
    }
}

5. Polymorphism with Abstract Classes

Vehicle vehicle = new Car();
vehicle.Start(); // Calls Car's Start method

6. Benefits of Abstract Classes and Methods

  • Encourage code standardization and reusability.
  • Define a structure that derived classes must follow.
  • Enable polymorphism for flexibility in using derived classes.
  • Allow selective overriding of methods.

Conclusion

Abstract classes and methods in C# are essential tools for creating organized and maintainable code. They provide a blueprint for derived classes while allowing flexibility and code reusability. By mastering these concepts and their practical use, you can develop more versatile and structured C# applications.