what is the difference between explicit and implicit interface implementation in c# - c#

what is the difference between explicit interface and implicit interface implementation in c#/asp.net? in which scenario we can use the explicit interface and implicit interface implementation.
Thanks,
Pradeep

The concept behind implicit and explicit implementation is rather simple:
A member with implicit implementation will be accessible through the interface as well as through the class implementing it
A member with explicit implementation will be accessible through the interface only
As for why and when you would use one or another, it depends. In the case you're implementing more than one interface with the same property/method, explicit implementation is your only option, as it is the only way to know which property/method you're intending to call. Obviously in this scenario you can't have that property/method on the class itself: if there is, it will be class only, and will not match any of the interfaces (which will have their explicit implementation of it).
In other scenarios, it really depends on your design choices and what you're trying to accomplish. If you want to force the caller to access interface members only through interface, and not through class declaration, do an explicit implementation.

Say you have two interfaces, IDoStuff<T> and IDoStuff, which your class implements. They both have a method "GetStuff", but one has the signature T GetStuff(), and the other has the signature object GetStuff().
The problem is that .net will not let you have two methods named the same thing that only differ on the return type. But you need to have both of these methods in your class to satisfy both interfaces. If T is, in fact, an object, then you can use explicit implementation like so.
public T GetStuff()
{
T stuff;
//Stuff Is Got
return stuff;
}
IDoStuff.GetStuff()
{
return (object)GetStuff();
}
Note that because IDoStuff mandates the security requirements of GetStuff, IDoStuff.GetStuff will be public/private/protected/internal based on that interface's declaration.
If you wanted, you could do every implantation explicitly, but the full method name for each would be InterfaceName.MethodName, and that gets a little annoying to read and write. Usually this is only used when you want to implement a method with the same signature multiple times to satisfy several interfaces.

Related

Interface marked as implemented in external lib, property from interface not visible, why? [duplicate]

What are the differences in implementing interfaces implicitly and explicitly in C#?
When should you use implicit and when should you use explicit?
Are there any pros and/or cons to one or the other?
Microsoft's official guidelines (from first edition Framework Design Guidelines) states that using explicit implementations are not recommended, since it gives the code unexpected behaviour.
I think this guideline is very valid in a pre-IoC-time, when you don't pass things around as interfaces.
Could anyone touch on that aspect as well?
Implicit is when you define your interface via a member on your class. Explicit is when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: IList.CopyTo would be implicitly implemented as:
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
and explicitly as:
void ICollection.CopyTo(Array array, int index)
{
throw new NotImplementedException();
}
The difference is that implicit implementation allows you to access the interface through the class you created by casting the interface as that class and as the interface itself. Explicit implementation allows you to access the interface only by casting it as the interface itself.
MyClass myClass = new MyClass(); // Declared as concrete class
myclass.CopyTo //invalid with explicit
((IList)myClass).CopyTo //valid with explicit.
I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.
I am sure there are more reasons to use/not use explicit that others will post.
See the next post in this thread for excellent reasoning behind each.
Implicit definition would be to just add the methods / properties, etc. demanded by the interface directly to the class as public methods.
Explicit definition forces the members to be exposed only when you are working with the interface directly, and not the underlying implementation. This is preferred in most cases.
By working directly with the interface, you are not acknowledging,
and coupling your code to the underlying implementation.
In the event that you already have, say, a public property Name in
your code and you want to implement an interface that also has a
Name property, doing it explicitly will keep the two separate. Even
if they were doing the same thing I'd still delegate the explicit
call to the Name property. You never know, you may want to change
how Name works for the normal class and how Name, the interface
property works later on.
If you implement an interface implicitly then your class now exposes
new behaviours that might only be relevant to a client of the
interface and it means you aren't keeping your classes succinct
enough (my opinion).
In addition to excellent answers already provided, there are some cases where explicit implementation is REQUIRED for the compiler to be able to figure out what is required. Take a look at IEnumerable<T> as a prime example that will likely come up fairly often.
Here's an example:
public abstract class StringList : IEnumerable<string>
{
private string[] _list = new string[] {"foo", "bar", "baz"};
// ...
#region IEnumerable<string> Members
public IEnumerator<string> GetEnumerator()
{
foreach (string s in _list)
{ yield return s; }
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
Here, IEnumerable<string> implements IEnumerable, hence we need to too. But hang on, both the generic and the normal version both implement functions with the same method signature (C# ignores return type for this). This is completely legal and fine. How does the compiler resolve which to use? It forces you to only have, at most, one implicit definition, then it can resolve whatever it needs to.
ie.
StringList sl = new StringList();
// uses the implicit definition.
IEnumerator<string> enumerableString = sl.GetEnumerator();
// same as above, only a little more explicit.
IEnumerator<string> enumerableString2 = ((IEnumerable<string>)sl).GetEnumerator();
// returns the same as above, but via the explicit definition
IEnumerator enumerableStuff = ((IEnumerable)sl).GetEnumerator();
PS: The little piece of indirection in the explicit definition for IEnumerable works because inside the function the compiler knows that the actual type of the variable is a StringList, and that's how it resolves the function call. Nifty little fact for implementing some of the layers of abstraction some of the .NET core interfaces seem to have accumulated.
Reason #1
I tend to use explicit interface implementation when I want to discourage "programming to an implementation" (Design Principles from Design Patterns).
For example, in an MVP-based web application:
public interface INavigator {
void Redirect(string url);
}
public sealed class StandardNavigator : INavigator {
void INavigator.Redirect(string url) {
Response.Redirect(url);
}
}
Now another class (such as a presenter) is less likely to depend on the StandardNavigator implementation and more likely to depend on the INavigator interface (since the implementation would need to be cast to an interface to make use of the Redirect method).
Reason #2
Another reason I might go with an explicit interface implementation would be to keep a class's "default" interface cleaner. For example, if I were developing an ASP.NET server control, I might want two interfaces:
The class's primary interface, which is used by web page developers; and
A "hidden" interface used by the presenter that I develop to handle the control's logic
A simple example follows. It's a combo box control that lists customers. In this example, the web page developer isn't interested in populating the list; instead, they just want to be able to select a customer by GUID or to obtain the selected customer's GUID. A presenter would populate the box on the first page load, and this presenter is encapsulated by the control.
public sealed class CustomerComboBox : ComboBox, ICustomerComboBox {
private readonly CustomerComboBoxPresenter presenter;
public CustomerComboBox() {
presenter = new CustomerComboBoxPresenter(this);
}
protected override void OnLoad() {
if (!Page.IsPostBack) presenter.HandleFirstLoad();
}
// Primary interface used by web page developers
public Guid ClientId {
get { return new Guid(SelectedItem.Value); }
set { SelectedItem.Value = value.ToString(); }
}
// "Hidden" interface used by presenter
IEnumerable<CustomerDto> ICustomerComboBox.DataSource { set; }
}
The presenter populates the data source, and the web page developer never needs to be aware of its existence.
But's It's Not a Silver Cannonball
I wouldn't recommend always employing explicit interface implementations. Those are just two examples where they might be helpful.
To quote Jeffrey Richter from CLR via C#
(EIMI means Explicit Interface Method Implementation)
It is critically important for you to
understand some ramifications that
exist when using EIMIs. And because of
these ramifications, you should try to
avoid EIMIs as much as possible.
Fortunately, generic interfaces help
you avoid EIMIs quite a bit. But there
may still be times when you will need
to use them (such as implementing two
interface methods with the same name
and signature). Here are the big
problems with EIMIs:
There is no documentation explaining how a type specifically
implements an EIMI method, and there
is no Microsoft Visual Studio
IntelliSense support.
Value type instances are boxed when cast to an interface.
An EIMI cannot be called by a derived type.
If you use an interface reference ANY virtual chain can be explicitly replaced with EIMI on any derived class and when an object of such type is cast to the interface, your virtual chain is ignored and the explicit implementation is called. That's anything but polymorphism.
EIMIs can also be used to hide non-strongly typed interface members from basic Framework Interfaces' implementations such as IEnumerable<T> so your class doesn't expose a non strongly typed method directly, but is syntactical correct.
I use explicit interface implementation most of the time. Here are the main reasons.
Refactoring is safer
When changing an interface, it's better if the compiler can check it. This is harder with implicit implementations.
Two common cases come to mind:
Adding a function to an interface, where an existing class that implements this interface already happens to have a method with the same signature as the new one. This can lead to unexpected behavior, and has bitten me hard several times. It's difficult to "see" when debugging because that function is likely not located with the other interface methods in the file (the self-documenting issue mentioned below).
Removing a function from an interface. Implicitly implemented methods will be suddenly dead code, but explicitly implemented methods will get caught by compile error. Even if the dead code is good to keep around, I want to be forced to review it and promote it.
It's unfortunate that C# doesn't have a keyword that forces us to mark a method as an implicit implementation, so the compiler could do the extra checks. Virtual methods don't have either of the above problems due to required use of 'override' and 'new'.
Note: for fixed or rarely-changing interfaces (typically from vendor API's), this is not a problem. For my own interfaces, though, I can't predict when/how they will change.
It's self-documenting
If I see 'public bool Execute()' in a class, it's going to take extra work to figure out that it's part of an interface. Somebody will probably have to comment it saying so, or put it in a group of other interface implementations, all under a region or grouping comment saying "implementation of ITask". Of course, that only works if the group header isn't offscreen..
Whereas: 'bool ITask.Execute()' is clear and unambiguous.
Clear separation of interface implementation
I think of interfaces as being more 'public' than public methods because they are crafted to expose just a bit of the surface area of the concrete type. They reduce the type to a capability, a behavior, a set of traits, etc. And in the implementation, I think it's useful to keep this separation.
As I am looking through a class's code, when I come across explicit interface implementations, my brain shifts into "code contract" mode. Often these implementations simply forward to other methods, but sometimes they will do extra state/param checking, conversion of incoming parameters to better match internal requirements, or even translation for versioning purposes (i.e. multiple generations of interfaces all punting down to common implementations).
(I realize that publics are also code contracts, but interfaces are much stronger, especially in an interface-driven codebase where direct use of concrete types is usually a sign of internal-only code.)
Related: Reason 2 above by Jon.
And so on
Plus the advantages already mentioned in other answers here:
When required, as per disambiguation or needing an internal interface
Discourages "programming to an implementation" (Reason 1 by Jon)
Problems
It's not all fun and happiness. There are some cases where I stick with implicits:
Value types, because that will require boxing and lower perf. This isn't a strict rule, and depends on the interface and how it's intended to be used. IComparable? Implicit. IFormattable? Probably explicit.
Trivial system interfaces that have methods that are frequently called directly (like IDisposable.Dispose).
Also, it can be a pain to do the casting when you do in fact have the concrete type and want to call an explicit interface method. I deal with this in one of two ways:
Add publics and have the interface methods forward to them for the implementation. Typically happens with simpler interfaces when working internally.
(My preferred method) Add a public IMyInterface I { get { return this; } } (which should get inlined) and call foo.I.InterfaceMethod(). If multiple interfaces that need this ability, expand the name beyond I (in my experience it's rare that I have this need).
In addition to the other reasons already stated, this is the situation in which a class is implementing two different interfaces that have a property/method with the same name and signature.
/// <summary>
/// This is a Book
/// </summary>
interface IBook
{
string Title { get; }
string ISBN { get; }
}
/// <summary>
/// This is a Person
/// </summary>
interface IPerson
{
string Title { get; }
string Forename { get; }
string Surname { get; }
}
/// <summary>
/// This is some freaky book-person.
/// </summary>
class Class1 : IBook, IPerson
{
/// <summary>
/// This method is shared by both Book and Person
/// </summary>
public string Title
{
get
{
string personTitle = "Mr";
string bookTitle = "The Hitchhikers Guide to the Galaxy";
// What do we do here?
return null;
}
}
#region IPerson Members
public string Forename
{
get { return "Lee"; }
}
public string Surname
{
get { return "Oades"; }
}
#endregion
#region IBook Members
public string ISBN
{
get { return "1-904048-46-3"; }
}
#endregion
}
This code compiles and runs OK, but the Title property is shared.
Clearly, we'd want the value of Title returned to depend on whether we were treating Class1 as a Book or a Person. This is when we can use the explicit interface.
string IBook.Title
{
get
{
return "The Hitchhikers Guide to the Galaxy";
}
}
string IPerson.Title
{
get
{
return "Mr";
}
}
public string Title
{
get { return "Still shared"; }
}
Notice that the explicit interface definitions are inferred to be Public - and hence you can't declare them to be public (or otherwise) explicitly.
Note also that you can still have a "shared" version (as shown above), but whilst this is possible, the existence of such a property is questionable. Perhaps it could be used as a default implementation of Title - so that existing code would not have to be modified to cast Class1 to IBook or IPerson.
If you do not define the "shared" (implicit) Title, consumers of Class1 must explicitly cast instances of Class1 to IBook or IPerson first - otherwise the code will not compile.
If you implement explicitly, you will only be able to reference the interface members through a reference that is of the type of the interface. A reference that is the type of the implementing class will not expose those interface members.
If your implementing class is not public, except for the method used to create the class (which could be a factory or IoC container), and except for the interface methods (of course), then I don't see any advantage to explicitly implementing interfaces.
Otherwise, explicitly implementing interfaces makes sure that references to your concrete implementing class are not used, allowing you to change that implementation at a later time. "Makes sure", I suppose, is the "advantage". A well-factored implementation can accomplish this without explicit implementation.
The disadvantage, in my opinion, is that you will find yourself casting types to/from the interface in the implementation code that does have access to non-public members.
Like many things, the advantage is the disadvantage (and vice-versa). Explicitly implementing interfaces will ensure that your concrete class implementation code is not exposed.
An implicit interface implementation is where you have a method with the same signature of the interface.
An explicit interface implementation is where you explicitly declare which interface the method belongs to.
interface I1
{
void implicitExample();
}
interface I2
{
void explicitExample();
}
class C : I1, I2
{
void implicitExample()
{
Console.WriteLine("I1.implicitExample()");
}
void I2.explicitExample()
{
Console.WriteLine("I2.explicitExample()");
}
}
MSDN: implicit and explicit interface implementations
Every class member that implements an interface exports a declaration which is semantically similar to the way VB.NET interface declarations are written, e.g.
Public Overridable Function Foo() As Integer Implements IFoo.Foo
Although the name of the class member will often match that of the interface member, and the class member will often be public, neither of those things is required. One may also declare:
Protected Overridable Function IFoo_Foo() As Integer Implements IFoo.Foo
In which case the class and its derivatives would be allowed to access a class member using the name IFoo_Foo, but the outside world would only be able to access that particular member by casting to IFoo. Such an approach is often good in cases where an interface method will have specified behavior on all implementations, but useful behavior on only some [e.g. the specified behavior for a read-only collection's IList<T>.Add method is to throw NotSupportedException]. Unfortunately, the only proper way to implement the interface in C# is:
int IFoo.Foo() { return IFoo_Foo(); }
protected virtual int IFoo_Foo() { ... real code goes here ... }
Not as nice.
The previous answers explain why implementing an interface explicitly in C# may be preferrable (for mostly formal reasons). However, there is one situation where explicit implementation is mandatory: In order to avoid leaking the encapsulation when the interface is non-public, but the implementing class is public.
// Given:
internal interface I { void M(); }
// Then explicit implementation correctly observes encapsulation of I:
// Both ((I)CExplicit).M and CExplicit.M are accessible only internally.
public class CExplicit: I { void I.M() { } }
// However, implicit implementation breaks encapsulation of I, because
// ((I)CImplicit).M is only accessible internally, while CImplicit.M is accessible publicly.
public class CImplicit: I { public void M() { } }
The above leakage is unavoidable because, according to the C# specification, "All interface members implicitly have public access." As a consequence, implicit implementations must also give public access, even if the interface itself is e.g. internal.
Implicit interface implementation in C# is a great convenience. In practice, many programmers use it all the time/everywhere without further consideration. This leads to messy type surfaces at best and leaked encapsulation at worst. Other languages, such as F#, don't even allow it.
One important use of explicit interface implementation is when in need to implement interfaces with mixed visibility.
The problem and solution are well explained in the article C# Internal Interface.
For example, if you want to protect leakage of objects between application layers, this technique allows you to specify different visibility of members that could cause the leakage.
I've found myself using explicit implementations more often recently, for the following practical reasons:
Always using explicit from the starts prevents having any naming collisions, in which explicit implementation would be required anyways
Consumers are "forced" to use the interface instead of the implementation (aka not "programming to an implementation") which they should / must do anyways when you're using DI
No "zombie" members in the implementations - removing any member from the interface declaration will result in compiler errors if not removed from the implementation too
Default values for optional parameters, as well constraints on generic arguments are automatically adopted - no need to write them twice and keep them in sync

Generic type constraints on an interface method

I'm doing the following in my interface, reason being I don't want to be tightly coupled to the implementation of IEquipment in my implementations of IEquipmentDataProvider
public interface IEquipmentDataProvider
{
IEquipment GetEquipment<E>(string Path) where E : IEquipment, new();
}
But I think that the type constraints should be left to the implementation and I should just declare IEquipment GetEquipment(string path); in my interface. However, if I do that it's an interface for a redundant method as that method will never get called.
Is it considered okay to implement type constraints in an interface method, or is there another pattern I should consider?
Edit:
The reason I'm doing this is because I don't want my data access layer to have to use a concrete implementation of IEquipment and I can leave that to the domain logic layer. Hence the use of the generics , which will be an instance of IEquipment but decided upon by dll. And called with
Equipment eq = da.GetEquipment<Equipment>("somepath"); // where eq is Iequipment, and da is IEquipmentDataProvider
But I think that the type constraints should be left to the implementation and I should just declare IEquipment GetEquipment(string path); in my interface.
While I can see what you mean, I do think it's relevant here. Ignoring your type constraints, your interface definition makes it painfully clear that this is intended to work with equipment:
IEquipmentDataProvider
GetEquipment()
Return type IEquipment
It's almost unavoidable that you'd want to limit the usable types to those that implement IEquipment.
Does the following make sense to you? Is this an intended use case?
public class StringProvider : IEquipmentDataProvider
{
//...
}
var provider = new StringProvider();
var equipment = provider.GetEquipment<string>(myPath);
I'm pretty sure that it doesn't. Because it doesn't make sense to use anything other than an IEquipment implementation.
I think the issue is bigger than you're currently discussing. I see some other minor inconsistencies:
You make a generic E type argument, yet your return value is of type IEquipment. Why? Why not make E the return type? Existing code such as IEquipment myEquipment = myProvider.GetEquipment() will still work without needing changes, and you have the optional benefit of returning a specific type should you ever need it.
I don't quite understand why the method is generic but the class/interface itself isn't. There are use cases for generic methods, but yours seems to fit a generic class/interface much better.
I want to further address the second bullet point. Your interface, when implemented, will ensure that every implementation can get every type of `IEquipment.
Compare this to the generic class version:
public interface IEquipmentDataProvider<E> where E : IEquipment, new()
{
E GetEquipment<E>(string Path);
}
Pretty much the same code. But now, you can implement these interfaces specifically or generically, however you want it:
public class HammerDataProvider : IEquipmentDataProvider<Hammer> {}
public class SawDataProvider : IEquipmentDataProvider<Saw> {}
public class AllEquipmentDataProvider : IEquipmentDataProvider<IEquipment> {}
Every implementation of IEquipmentDataProvider can choose to either limit itself to a specific type (Hammer, Saw), or it can handle every implementation of IEquipment.
Edit
This also allows you to combine multiple interfaces, which can be implemented separately in the same class:
public class HammerAndSawDataProvider : IEquipmentDataProvider<Hammer>, IEquipmentDataProvider<Saw> {}
Due to a lack of type distinction between the two interface methods, you'll need to rely on explicit interface implementation. Maybe not what you want.
If your interface method had had different signatures between different generic types (e.g. GetEquipment<E>(E myEquipment) ), then you could've avoided needing to use explicit interface implementation.
This may be one step too far for your requirements, but it does showcase that you get absolute control over which equipment can be handled by a specific provider.
To summarize
The type constraint seems to be a given, based on the naming that you've used for the class and method.
It would make little to no sense to ever use a type that deviates from the suggested type constraint.
If you're already using a generic type; you're better off having your return type be the generic type. At worst, it doesn't break anything. At best, it allows for better type safety and less hard casting (e.g. it removes the need for performing a cast in Hammer myHammer = (Hammer)provider.GetEquipment(myPath);).
More often than not, you'll want to use the generic parameter at the class/interface level. The main drawback of generic methods (without a generic class) is that you have to repeatedly define a type constraint for every submethod that is called in the toplevel method. Generic methods (without a generic class) are generally only really warranted in "toolkit" methods, as far as I can think of right now.
Pedantic: I would rename the generic parameter to TEquipment (or TE if you want to be terse). Type parameters are usually named in a way that e.g. TElement is read as "type of the Element". But this is a matter of style and naming convention.
In your code, you do adhere to the "interface names begin with I" convention. Generic types have a similar convention about beginning with T.
Response to OP's update
Edit: The reason I'm doing this is because I don't want my data access layer to have to use a concrete implementation of IEquipment and I can leave that to the domain logic layer. Hence the use of the generics , which will be an instance of IEquipment but decided upon by dll.
This somewhat reaffirms my assertion that you should use a generic class/interface, not just a generic method.
If one were to paraphrase this line of code,
IEquipment GetEquipment<E>(string Path) where E : IEquipment, new();
it would become "a GetEquipment generic method with a constraint of type IEquipment with an implementation that has a default constructor".
Instead, the design could simply be an explicit interface method
Equipment eInstance=new Equipment();
IEquipmentDataProvider iEInstance=(IEquipmentIEquipmentDataProvider )eInstance;
iEInstance=iEInstance.GetEquipment(path);
so that, even if you have another class implementing the GetEquipment method differently, you could simply call the right GetEquipment method of IEquipment by using the explicit interface method.
Edit: after the OP's edit
EquipmentDataProvider edp=new EquipmentDataProvider();
IEquipmentDataProvider da=(IEquipmentDataProvider)edp; // An explicit method invocation to ensure that the EquipmentataProvider's GetEquipment and not some other Equipment class' GetEquipment is called. This is what is the intent of the
Equipment eq = da.GetEquipment<Equipment>("somepath");

Is the use of explicit interface implementation meant for hiding functionality?

I use interfaces for decoupling my code. I am curious, is the usage of explicit interface implementation meant for hiding functionality?
Example:
public class MyClass : IInterface
{
void IInterface.NoneWillCall(int ragh) { }
}
What is the benefit and specific use case of making this available only explicitly via the interface?
There are two main uses for it in my experience:
It allows you to overload methods by return value. For example, IEnumerable<T> and IEnumerable both declare GetEnumerator() methods, but with different return types - so to implement both, you have to implement at least one of them explicitly. Of course in this question both methods are provided by interfaces, but sometimes you just want to give a "normal" method with a different type (usually a more specific one) to the one from the interface method.
It allows you to implement part of an interface in a "discouraging" way - for example, ReadOnlyCollection<T> implements IList<T>, but "discourages" the mutating calls using explicit interface implementation. This will discourage callers who know about an object by its concrete type from calling inappropriate methods. This smells somewhat of interfaces being too broad, or inappropriately implemented - why would you implement an interface if you couldn't fulfil all its contracts? - but in a pragmatic sense, it can be useful.
One example is ICloneable. By implementing it explicitly, you can have still have a strongly typed version:
public class MyClass : ICloneable {
object ICloneable.Clone() {
return this.Clone();
}
public MyClass Clone() {
return new MyClass() { ... };
}
}
It is not meant for hiding methods but to make it possible to implement two methods with the same signature/name from different interface in to different ways.
If both IA and IB have the operation F you can only implement a different method for each F by explicitly implementing the interfaces.
It can be used for hiding. For example, some classess that implement IDisposable do so explicitly because they also have a Close() method which does the same thing.
You can also use the explicit interface definitions for when you are implementing two interfaces on one class and there is a signature clash and the functionality differs depending on the interface. However, if that happens it is usually a sign that your class is doing too much and you should look at splitting the functionality out a bit.

Should I implement interface members explicitly or implicitly?

This question and Eric Lippert's answer got me wondering: How do you decide whether to use an explicit or implicit implementation when implementing methods of an interface?
(personally) I only see a need for explicit implementations when there is a clash between methods with the same signature.
For example, when implementing IEnumerable<T>, you should implement 2 methods GetEnumerator() which have the same signature, except for the return type. So you'll have to implement IEnumerable.GetEnumerator() explicitly:
public abstract class MyClass<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
return ...;
}
IEnumerator IEnumerable.GetEnumerator() // explicit implementation required
{
return GetEnumerator();
}
}
Another use for an explicit implementation is if you don't want the method to be called through an object instance, but only through an interface. I personally think this doesn't make much sense, but in some very rare cases, it can be useful.
Philippe's answer is a practical, one, however, there are architectural considerations as well.
Interfaces are used to make classes compatible so that they can be consumed by other objects. If only those consuming objects need the functionality of the interface, then it should be restricted so - by the principle of least privilege. If would be unnecessary to expose that interface method to all other users of the class.
Paul
Another case for explicit interfaces is where the object needs to implement an interface to accept calls from an internal object, but you don't want to expose those as part of your API.

implicit vs explicit interface implementation [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C#: Interfaces - Implicit and Explicit implementation
Would someone explain the differences between these two beasts and how to use them. AFAIK, many pre.2.0 classes were implemented without generic types, thus causing latter version to implement both flavors of interfaces. Is the the only case why one would need to use them?
Can you also explain in depth how to use them.?
Thanks
There is a good and pretty detailed blog post about this.
Basically with implicit interface implementation you access the interface methods and properties as if they were part of the class. With explicit interface implementations you can only access them when treating it as that interface.
In terms of when you would use one over the other, sometimes you have to use explicit interface implementation as you either have a property/method with same signature as the interface or you want to implement two interfaces with the same signatures and have different implementations for those properties/methods that match.
The below rules are from Brad Abrams design guidelines blog.
Do not use explicit members as a security boundary. They can be called by any client who cast an instance to the interface.
Do use explicit members to hide implementation details
Do use explicit members to approximate private interface implementations.
Do expose an alternative way to access any explicitly implemented members that subclasses are allowed to override. Use the same method name unless a conflict would arise.
It's also mentioned in the comments in Brad's blog that there is boxing involved when using explicit implementation on value types so be aware of the performance cost.
In layman's terms, if a class inherits from 2 or more interfaces and if the interfaces happen to have the same method names, the class doesn't know which interface method is being implemented if you use implicit interface implementation. This is one of the scenarios when you would explicitly implement an interface.
Implicit Interface Implementtation
public class MyClass : InterfaceOne, InterfaceTwo
{
public void InterfaceMethod()
{
Console.WriteLine("Which interface method is this?");
}
}
interface InterfaceOne
{
void InterfaceMethod();
}
interface InterfaceTwo
{
void InterfaceMethod();
}
Explicit Interface Implementation
public class MyClass : InterfaceOne, InterfaceTwo
{
void InterfaceOne.InterfaceMethod()
{
Console.WriteLine("Which interface method is this?");
}
void InterfaceTwo.InterfaceMethod()
{
Console.WriteLine("Which interface method is this?");
}
}
interface InterfaceOne
{
void InterfaceMethod();
}
interface InterfaceTwo
{
void InterfaceMethod();
}
The following link has an excellent video explaining this concept
Explicit Interface Implementation
There is one more way to look at it, from the labyrinthine implementation itself, here: http://blogs.msdn.com/cbrumme/archive/2003/05/03/51381.aspx.
But in short, implicit implementation gives you an is-a type conversion, explicit implementation won't be accessible unless the object is explicitly type cast to that interface type.

Categories