Junior — Middle
What should be done if two interfaces with the same method names are declared in a class?
sobes.tech AI
Answer from AI
If a class implements two interfaces containing methods with the same names and signatures, then:
- If the methods have the same signature and return type, it is sufficient to implement one method that satisfies both interfaces.
- If methods with the same names have different signatures (e.g., different parameters), then both methods need to be implemented separately.
- If interfaces contain methods with the same names and signatures but with different default implementations, then the class must explicitly override this method and specify which implementation to use, or provide its own.
Example with conflict of default methods:
interface IFirst {
void Method() => Console.WriteLine("First");
}
interface ISecond {
void Method() => Console.WriteLine("Second");
}
class MyClass : IFirst, ISecond {
public void Method() {
// Explicitly choose an implementation
((IFirst)this).Method();
// or provide its own implementation
Console.WriteLine("MyClass Method");
}
}
Thus, when there is a conflict of method names from different interfaces in C#, the class must explicitly resolve the ambiguity by implementing the method itself.