Wednesday, December 2, 2009

Implementation of two interface having the same method signature in the same class

If the signature of the methods in two different interfaces are same and both the interfaces are going be implemented in the same class. Following is the two interfaces:
public interface Interface1 { string PrintName(); }
public interface Interface2 { string PrintName(); }
From the above code we can infer that we have two interface with names Interface1 and Interface2 and both have a single method named “PrintName”. The signatures of both the methods are same and we need to implement the interfaces in our class “myClass”. One way of implementing the interface is as shown below (just having a “public” implementation of the interface method only once).
public class myClass : Interface1, Interface2
{
public myClass() { }
public string PrintName() { return this.GetType().Name; }
}
The above implementation has got a limitation i.e the method “PrintName” is considered to be a common method for all i.e common method for the class, and for the interfaces Interface1 and Interface2. If you are writing a code shown below
myClass myclass = new myClass ();
Interface1 i1 = new myClass ();
Interface2 i2 = new myClass ();
Console.WriteLine(myclass.PrintName());
Console.WriteLine(i1.PrintName());
Console.WriteLine(i2.PrintName());
All the calls to method “PrintName” will give you the same result, the name of the class i.e. “myClass”. This is because all call to the method goes to the same definition. Now if you want to give different implementation to the methods in interface Interface1 and Interface2; you have two implementations of the same method and prefix the method names with the interface name as shown below.
public class myClass : Interface1, Interface2
{
public myClass() { }
string Interface1.PrintName() { return “Interface1 PrintName Method”; }
string Interface2.PrintName() { return “Interface2 PrintName Method”; }
}
Now the below code will give you different output.
Interface1 i1 = new myClass();
Interface2 i2 = new myClass();
Console.WriteLine(i1.PrintName());// Will print " Interface1 PrintName Method"
Console.WriteLine(i2.PrintName());// Will print " Interface2 PrintName Method"
So this is how two interfaces having the same method signature can be given different implementation in the same class.

No comments: