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”.
public class BaseClass{ //}public interface IMyInterface{ //}public class DerivedClass : IMyInterface, BaseClass //ERROR HERE : CS1722: Base class 'BaseClass' must come before any interface.{ //}
public class BaseClass
{
//
}
public interface IMyInterface
public class DerivedClass : IMyInterface, BaseClass //ERROR HERE : CS1722: Base class 'BaseClass' must come before any interface.
Why is it necessary to extend the class first and then implement the inteface?
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.