How to choose whether to implement an interface or explicitly implement an interface?

There are two ways to implement an interface:

interface IMyInterface { void Foo(); } class IImplementAnInterface : IMyInterface { public void Foo() { } } // var foo = new IImplementAnInterface(); // foo.Foo(); //Ok // ((IMyInterface)foo).Foo(); //Ok class IExplicitlyImplementAnInterface : IMyInterface { void IMyInterface.Foo() { } } // var foo = new IExplicitlyImplementAnInterface(); // foo.Foo(); //ERROR! // ((IMyInterface)foo).Foo(); //Ok 

The difference is that if an interface is explicitly implemented, it must actually be passed as that interface before anyone can call the Foo method.

How to decide what to use?

+4
source share
4 answers

If there are collisions (two interfaces have a method with the same signature, or your class / base class and interface collide the same way), and you do not want the colliding methods to have the same bodies, then you should use explicit interfaces.

Otherwise, you are free to choose. If you want to hide some implemented methods, you choose an explicit method. For example, the Dictionary <,> class does this with some of the ICollection <> interface methods, because hidden methods confuse people.

+5
source

There are times when you need to provide an explicit implementation, for example, when implementing IEnumerable and IEnumerable <>, where both interfaces expose the GetEnumerator method.

The following general rule: if I implement an interface, but provide additional more convenient and typical methods and properties to reveal the functionality of the interface, I would explicitly implement the interface. This provides an open interface that makes the class more suitable, but allows you to use algorithms that can rely on the implemented interface to access the methods and properties provided by the interface.

It was hard to say, but I hope it makes sense.

+2
source

I would recommend this only in cases where multiple interfaces are implemented, and both of them contain a method with the same name.

You can also explicitly implement a method to effectively "hide" it and implement an equivalent method with a better name. System.IO.Stream does this by implementing Dispose explicitly and providing the closer name Close ().

For more information, see the MSDN article: http://msdn.microsoft.com/en-us/library/ms229034.aspx .

+1
source

This is most often seen as a workaround for .NET that prohibits covariance of the return type.

0
source

Source: https://habr.com/ru/post/1333719/


All Articles