Information Technology Reference
In-Depth Information
Implementing Interfaces with Duplicate Members
Since a class can implement any number of interfaces, it is possible that two or more of the
interface members might have the same signature and return type. How does the compiler
handle that situation?
For example, suppose you had two interfaces— IIfc1 and IIfc2 —as shown following.
Each interface has a method named PrintOut , with the same signature and return type. If you
were to create a class that implemented both interfaces, how should you handle these dupli-
cate interface methods?
interface IIfc1
{
void PrintOut(string s);
}
interface IIfc2
{
void PrintOut(string t);
}
The answer is that if a class implements multiple interfaces, where several of the interfaces
have members with the same signature and return type, the class can implement a single
member that satisfies all the interfaces containing that duplicated member.
For example, the following code shows the declaration of class MyClass , which implements
both IIfc1 and IIfc2 . Its implementation of method PrintOut satisfies the requirement for both
interfaces.
class MyClass : IIfc1, IIfc2 // Implement both interfaces
{
public void PrintOut(string s) // Single implementation for both
{
Console.WriteLine("Calling through: {0}", s);
}
}
class Program
{
static void Main()
{
MyClass mc = new MyClass();
mc.PrintOut("object.");
}
}
Search WWH ::




Custom Search