Pages

Friday, March 7, 2014

Interview Questions C# - Can a class implement interfaces with same method signatures?

Objective

  • To understand the behavior of C# classes when implementing interfaces with same method signatures
  • To know the best practices when implementing interfaces with same method signatures
For us to understand C# behavior when implementing interfaces with same method signatures please take a look at these two(2) interfaces:

interface Interface1{
       void Method1();
}


interface Interface2{
       void Method1();
}


class Class1:Interface1, Interface2{
      void Method1(){
             Console.WriteLine("this method is called");
      }
}


In our Main Class:

public static void Main(string[] args){
      Interface1 interface1 = new Class1();
      Interface2 interface2 = new Class1();
      interface1.Method1();
      interface2.Method2();
Console.ReadLine(); }
When you hit "F5" when you go to Debug > Start Debugging you will see this result.




The answer to our question "Can a class implement interfaces with same method signature?" is "Yes" but,  what if you want different implementation for same method signatures?

Then you should Implement it Explicitly by modifying your Base Class Similar to this:

class Class1:Interface1, Interface2{
      void Interface1.Method1(){
  Console.WriteLine("Implemented Method From Interface1");
}
      void Interface2.Method1(){
  Console.WriteLine("Implemented Method From Interface2");
} }
The result will then be:
















Conclusion:

  • A class can implement interfaces with same method signatures
  • we can apply explicit implementation when we are aiming for different implementation of interfaces with same method signatures


No comments:

Post a Comment