If a class implements two interfaces which contain a method with the same signature and the class itself is having a method with the same signature, then implementing that method to the class leads to error. Explicit implementation is used to resolve this case. It’s nothing but calling the interface method name in a fully qualified manner. Call the method along with the interface name.
using System;
interface IMyinterface1
{
void display();
}
interface IMyinterface2
{
void display();
}
class trial:IMyinterface1,IMyinterface2
//interface implemented
{
public void display()
//Method belongs to class trial
{
Console.WriteLine("Method from class trial");
}
void IMyinterface1.display()
//explicit member implementation
{
Console.WriteLine("Method from Interface - IMyinterface1");
}
void IMyinterface2.display()
//explicit member implementation
{
Console.WriteLine("Method from Interface - IMyinterface2");
}
}
class sample
{
public static void Main()
{
IMyinterface1 i1 = new trial();
//creating reference to interface
i1.display();
//calling interface method
IMyinterface2 i2 = new trial();
//creating reference to interface
i2.display();
//calling interface method
trial t = new trial();
t.display();
}
}
For Answers, see/post comments
Explicit Member Implementation in C#
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment