Explain the differences between an abstract class and an interface in C# and discuss when you would use each one.

1 Answers
Answered by suresh

Differences between Abstract Class and Interface in C# - Interview Question

Differences between Abstract Class and Interface in C#

An abstract class in C# is a class that cannot be instantiated on its own and may contain abstract members (methods, properties, events). An interface, on the other hand, is a contract that defines the properties and methods that a class must implement.

Key Differences:

  1. An abstract class can have a mix of abstract and non-abstract members, while an interface can only have abstract members.
  2. A class can inherit only one abstract class, but can implement multiple interfaces.
  3. An abstract class can have access modifiers for its members, while an interface cannot.
  4. An abstract class can provide default implementations for its members, while an interface cannot.

When to Use Each One:

Use an abstract class when you want to provide a default implementation for some methods and have some concrete behavior that subclasses can inherit. Use an interface when you want to define a contract that multiple classes can implement, without providing any default implementation.

In summary, use an abstract class when you have a "is-a" relationship between the base and derived classes and use an interface when you have a "has-a" relationship or need to implement multiple contracts.

Answer for Question: Explain the differences between an abstract class and an interface in C# and discuss when you would use each one.