public interface IDoSomething
{
void DoIt();
}
You are probably already aware that we can implicitly implement the interface with code like:
{
void DoIt();
}
public class MyClass : IDoSomething
{
public void DoIt()
{
throw new NotImplementedException();
}
}
We can use the implementation like:
{
public void DoIt()
{
throw new NotImplementedException();
}
}
MyClass myClass = new MyClass();
myClass.DoIt();
If MyClass is to explicitly implement the interface, the MyClass implementation would look like:
myClass.DoIt();
public class MyClass : IDoSomething
{
void IDoSomething.DoIt()
{
throw new NotImplementedException();
}
}
Notice the two differences.
{
void IDoSomething.DoIt()
{
throw new NotImplementedException();
}
}
- The access modifier has been dropped from the DoIt method signature
- The DoIt method name is now qualified with the interface name
IDoSomething myClass = new MyClass();
myClass.DoIt();
Or you could cast the MyClass instance back to its interface to call the DoIt method, as shown in the following snippet:
myClass.DoIt();
MyClass myClass = new MyClass();
((IDoSomething) myClass).DoIt();
So, what are the benefits of explicitly implementing an interface?
((IDoSomething) myClass).DoIt();
- As the implementer of a class, you can try to force good practice on clients by making them code to an interface
- As a consequence of the point above, you can reduce tight coupling in your code as it shouldn't be using concrete implementations directly
- If you are implementing two interfaces which have the same method signatures, or a method signature in an interface clashes with one already visible in your class, you can separate the two methods
No comments:
Post a Comment