C# provides the ability to implement a class from mulitiple interfaces which greatly increases a classes ability to be consumed by potential callers. Unfortunately, every now and then we run into a situation where an interface has the exact same function signature as another interface. Rather than changing the function name on one of the interfaces and potentially causing issues with other pieces of code, we can consume both function requirements using the strategy outlined in this article.
Lets say you have two interfaces that contain a function with an identical signature. Meaning they have the same name, same return type and the same parameter list as seen below:
public interface Interface1
{
void Function(string param1);
}
public interface Interface2
{
void Function(string param1);
}
If you intend on being able to access each interface's function independently, you need to use code similiar to below:
public class MyClass : Interface1, Interface2
{
void Interface1.Function1(string param1)
{
//perform function operations for interface 1
}
void Interface2.Function1(string param1)
{
//perform function operations for interface 2
}
}
This strategy is called Explicit Interface Implementation. By declaring functions like this, you now have access to each interface's functions but these functions can NOT be declared as public and therefore can NOT be called by a class instance. In order to call the proper function you need to use code like this:
public static void Main()
{
//Declare a class instance MyClass
MyClass myClass = new MyClass();
//Declare an interface instance "Interface1" using myClass
Interface1 myInterface = (Interface1)myClass;
//This line will crash the compiler because you can't access Function1 through a class instance
myClass.Function1("param1");
//However this line will NOT crash the compiler and will execute the function you intended
myInterface.Function1("param1");
}
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5