I have two options in VS2010 for implementing interfaces.
When I have IHelper.cs interface as follows:
public interface IHelper
....
IEnumerable<IPort> Ports { get; }
"Implement Interface Explicitly" gives this code:
IEnumerable<IPort> IHelper.Ports
{
get
{
...
}
}
And, "Implement Interface" gives me this code:
public IEnumerable<IPort> Ports
{
get
{
...
}
}
Are they the same or different? Why do I have two options in implementing interfaces in C#?
An explicit interface implementation is a class member that is only called through the specified interface. Name the class member by prefixing it with the name of the interface and a period. For example: C# Copy.
Resolving conflicts here ..... "Implicit Implementation" - means just simple implementation of a particular method having same name and same signature which belongs to the same class itself, where as "Explicit Implementation" - means implementation of a method using their Interface name having same name and signature ...
Explicit permissions are permissions that are set by default when the object is created, or by user action. Inherited permissions are permissions that are given to an object because it is a child of a parent object.
Interface is a contract and anywhere where you can access the interface, you should be able to access all the methods in it. In other words, all the methods declared in the interface are supposed to be public so it doesn't make sense stating it explicitly.
Explicit interface declarations mean that the interface members are not available on types other than the interface itself, so implementing types would need to be cast to the interface before accessing them publicly.
Implicit, the standard way in which most interfaces are implemented, exposes interface items on the implementor-type's public API.
The main reason for explicit interface definitions is to avoid naming conflicts if you happen to implement two interfaces that contain methods with the same signature... the explicit definition allows the compiler to keep the signatures distinct enough to resolve.
A secondary reason that supports code maintenance, as suggested by XenoPuTtSs in the comments, is that explicit definitions will trigger compiler errors on the implementing types if the method signature is removed. On implicit implementations, removing a method from the interface will leave the method as a regular member of any types - meaning you need to search manually for now-defunct method implementations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With