Naimish Makwana
C# - Why base class must come before any interfaces when declaring a derived class?

When we are implementing both interface and base class in any derived class than we must have to follow the sequnce where we have to first put base class and than Interface.
Ex: If we don’t follow the sequnce than we will get error “Base class must come before any interface”.

  1. public class BaseClass
  2. {
  3. //
  4. }
  5. public interface IMyInterface
  6. {
  7. //
  8. }
  9. public class DerivedClass : IMyInterface, BaseClass //ERROR HERE : CS1722: Base class 'BaseClass' must come before any interface.
  10. {
  11. //
  12. }

Why is it necessary to extend the class first and then implement the inteface?

By Naimish Makwana in C# on Jan 12 2023
  • Tuhin Paul
    Feb, 2023 22

    In C#, the base class must come before any interfaces when declaring a derived class because of the way that the C# compiler resolves method calls.

    When a method is called on an object, the compiler first looks for the method in the derived class. If the method is not found in the derived class, the compiler then looks in the base class. If the method is not found in the base class, the compiler then looks in any interfaces that the class implements.

    If the order of the base class and interfaces is reversed, the compiler would not know which method to call when a method is called on an object that implements both the base class and an interface with the same method signature. This could lead to unexpected behavior and potential runtime errors.

    By enforcing the rule that the base class must come before any interfaces, the C# compiler ensures that method resolution is unambiguous and that the correct method is called when a method is called on an object that implements both the base class and an interface with the same method signature.

    • 4


Most Popular Job Functions


MOST LIKED QUESTIONS