Here’s the story. I created an interface, IVehicle. I explicitly implemented the interface in my class, Vehicle.cs.
Here is my interface:
Interface IVehicle
{
int getWheel();
}
here is my class:
class Vehicle: IVehicle
{
public int IVehicle.getWheel()
{
return wheel;
}
public void printWheel()
{
Console.WriteLine(getWheel());
}
}
Notice that getWheel() is explicitly implemented. Now, when I try to call that method within my Vehicle class, I receive an error indicating that getWheel() does not exist in the current context. Can someone help me understand what I am doing wrong?
When you explicitly implement the interface, you first have to cast the object to the interface, then you can call the method. In other words, the method is only available when the method is invoked on the object as the interface type, not as the concrete type.
See this reference at MSDN for more information. Here’s the relevant snippet:
For what it’s worth — this probably isn’t a particularly good use of explicit interface implementation. Typically, you want to use explicit implementation when you have a class that has a full interface for typical operations but also implements an interface that may supersede some of those operations. The canonical example is a
Fileclass that implementsIDisposable. It would have aClose()method but be required to implementDispose(). When treating as aFileyou would useOpen/Close. When opened in a using statement, however, it will treat it as anIDisposableand callDispose. In this caseDisposesimply callsClose. You wouldn’t necessarily want to exposeDisposeas part of theFileimplementation since the same behavior is available fromClose.