In this post, I’ll show the differences between standard interface implementation and explicit interface implementation.
Let’s say we have a IShape interface with one method called Print() as followed
public interface IShape
{
void Print();
}
Standard implementation
Let’s say we have a class called Triangle which implements the IShape interface. In the standard implementation, the class would look like this.
public class Triangle : IShape
{
public void Print()
{
Console.Write("Triangle");
}
}
When we create an instance of Triangle and assign it to a Triangle type variable or assign it to a IShape type variable, calling the Print() would print the same result;
Explicit implementation
In explicit implementation, it is slightly different. The Print() method will be marked as IShape.Print() instead. It also does not have a public modifier as explicit implementation of the interface is automatically public.
public class Triangle : IShape
{
void IShape.Print()
{
Console.Write("Triangle");
}
}
Explicit implementation means the Print method is explicitly associated with the IShape interface. The class will also behave differently. You can no longer call the Print() method from an instance of Triangle. You will get a compile error. However, you can either cast it to IShape or assign the instance to an IShape type variable and then you’ll be able to call the Print() method.
So why explicit implementation?
In most cases you just want the standard implementation but there are times you must use explicit implementation. If you have a class that implements 2 interfaces with same method name and parameters but different return types (if same return types and different parameters, they are treated as overload methods), you must implement one of them (or both) explicitly so the compiler knows which method you want to call when you use it.
public interface ITriangle
{
string Print();
}
public interface IShape
{
void Print();
}
public class Triangle : IShape, ITriangle
{
void IShape.Print()
{
Console.Write("Triangle");
}
public string Print()
{
return "Triangle from ITriangle";
}
}