Sobes.tech
Middle+

Tell about the difference between interfaces and abstract classes. Why was default implementation introduced in interfaces?

sobes.tech AI

Answer from AI

Interfaces and abstract classes are different mechanisms for defining contracts and partial implementations in object-oriented programming.

Interfaces:

  • Define a set of methods that a class must implement.
  • Do not contain state (fields).
  • Before C# 8.0, they could not contain method implementations, only declarations.
  • Allow multiple inheritance of interfaces.

Abstract classes:

  • Can contain both abstract methods (without implementation) and methods with implementation.
  • Can contain fields and state.
  • Support inheritance, but a class can only inherit from one abstract class.

Default interface methods: Introduced in C# 8.0 to solve the problem of extending interfaces without breaking existing code. Now, new methods with implementations can be added to interfaces, and classes that already implement this interface will not break.

This allows:

  • Adding new functionalities to interfaces without the need to change all implementations.
  • Making interfaces more flexible and extensible.

Example:

public interface ILogger
{
    void Log(string message);
    
    // Default implementation
    void LogError(string error) => Log($"Error: {error}");
}

Thus, default implementation helps evolve interfaces while maintaining backward compatibility.

Tell about the difference between interfaces and… - sobes.tech