25 Feb 2024




Beginner

In C#, both abstract classes and interfaces are used to define contracts for classes, but they have some key differences in their usage and implementation:

  • Abstract Class:
    • An abstract class is a class that cannot be instantiated directly. It serves as a blueprint for other classes and may contain a mixture of implemented methods and abstract methods.
    • Abstract methods are declared using the abstract keyword and must be implemented by any derived classes.
    • Abstract classes can contain constructors, fields, and methods with various access modifiers.
    • A class can inherit from only one abstract class due to C#'s single inheritance model.

Example:

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

    public void Eat()
    {
        Console.WriteLine("Animal is eating.");
    }
}
  • Interface:
    • An interface, unlike abstract classes, contains only method and property declarations, without any implementation.
    • Interfaces define a contract that classes can implement explicitly, specifying the members a class must support.
    • In C#, a class can implement multiple interfaces.
    • Interfaces cannot contain fields or constructors.

Example:

public interface IShape
{
    double GetArea(); // Method declaration
    double GetPerimeter(); // Method declaration
}

Summary: abstract classes provide a way to partially implement classes, allowing derived classes to extend and specialize them. Interfaces define a contract for classes to adhere to, facilitating polymorphic behavior and allowing unrelated classes to be treated interchangeably if they implement the same interface. Choosing between them depends on the design requirements and the level of abstraction needed in your application.

c-sharp
abstract-class
interface