Implicit VS Explicit Interface Implementation

implicit vs explicit interface implementation

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.

C# Interfaces. Implicit implementation versus Explicit implementation

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.

Difference between implicit and explicit implementation of C# interfaces

Another aspect of this:

If you implicitly implemented, it means that the interface members are accessible to users of your class without them having to cast it.

If it's explicitly implemented, clients will have to cast your class to the interface before being able to access the members.
Here's an example of an explicit implementation:

    interface Animal
{
void EatRoots();
void EatLeaves();
}

interface Animal2
{
void Sleep();
}

class Wombat : Animal, Animal2
{
// Implicit implementation of Animal2
public void Sleep()
{
}

// Explicit implementation of Animal
void Animal.EatRoots()
{

}

void Animal.EatLeaves()
{
}

}

Your client code

Wombat w = new Wombat();
w.Sleep();
w.EatRoots(); // This will cause a compiler error because it's explicitly implemented
((Animal)w).EatRoots(); // This will compile

interface implementation: implicit vs explicit

Why I don't have an error having a class with two methods with the same name and signature?

Because that's how explicit interface implementation works. It allows you to have two versions of the same method. The method used is determined by what the type of reference used to invoke it was.

When I'm using var keyword, how does the compiler choses which method to call?

It is using type inference. The documentation states:

Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement

So its going to use whatever type the right hand side returned

What are the benefits?

Most of the time, none. But if you want your object to act differently when accessed through a certain interface, this is the way to do it.

Implicit Explicit interface

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

When you implement an interface in Java is it explicit or implicit?

Nope Java is implicit. Explicit is where you are implementing multiple interfaces that have the same method signatures in them and you explicitly state which interface the implementation is for.

An example from MSDN:

public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}

Here we have two Paint() methods, one from each interface. In Java you can only have one Paint() implementation. In C# you have the option of implementing versions for each interface so you get different behaviour depending how the class is called.

So if I called:

SampleClass c = new SampleClass();
((IControl)c).Paint();
((ISurface)c).Paint();

I'd get "IControl.Paint" printed out followed by "ISurface.Paint" printed out.

implicit internal interface implementation

The modifier must be public because the interface is public.

While that would have been a way of determining it: that isn't what the compiler wants. For implicit interface implementation (regardless of the visibility of the interface type), a member must be declared as public, no "ifs", "buts" or "maybes" (the implementing type, however, can be any visibility level)

Absolutely the language designers could have looked at more complex rules, but: since there is also an option for explicit interface implementation, they presumably didn't feel that it was necessary to do so.


Specifically, this is §18.6.5 ("Interface mapping") in the specification (v5) - emphasis mine ("I"=interface type, "M"=member, "S"=implementing type):

  • If S contains a declaration of an explicit interface member implementation that matches I and M, then
    this member is the implementation of I.M.
  • Otherwise, if S contains a declaration of a non-static public member that matches M, then this member
    is the implementation of I.M. If more than one member matches, it is unspecified which member is
    the implementation of I.M. This situation can only occur if S is a constructed type where the two
    members as declared in the generic type have different signatures, but the type arguments make their
    signatures identical.

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

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.

implicit vs explicit interfaces

Some considerations that came to my mind for why you could prefer the Case 1:

  • If CoolClass is not a pure interface, i.e. part of implementation is also inherited (though you might provide it for Case 2/3 too, e.g. in the form of a base class);
  • if there are reasons to have CoolClassUser implemented in a binary rather than a header (and that's not only protection but could also be code size, control of resources, centralized error handling etc.);
  • if you want to store the pointers and use it later, then also Case 1 seems better: (a) it's easier to keep them all in the same container, and (b) you would need to store the actual data type as well, and for Case 2/3 the solution that comes to mind is to convert it to "explicit" interface (i.e. Case 1) with help of a template wrapper.

Reasons why Case 2/3 might be preferrable:

  • if you later decide that worthless() is now worth something, and start using it, in Case 2 you will get compile-time errors for classes where it's not implemented. In Case 1, nothing will remind you to implement these functions for real, except maybe run-time errors if you are (un)lucky.
  • Case2/3 might have slightly better performance, though at the expense of bigger code size.

In some cases, it might be purely the matter of personal preferences, either yours or your users.



Related Topics



Leave a reply



Submit