C# Interfaces. Implicit Implementation Versus Explicit Implementation

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.

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.

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

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.

Implement Interface vs Implement Interface Explicitly in C#

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.

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

Why implement interface explicitly?

If you implement two interfaces, both with the same method and different implementations, then you have to implement explicitly.

public interface IDoItFast
{
void Go();
}
public interface IDoItSlow
{
void Go();
}
public class JustDoIt : IDoItFast, IDoItSlow
{
void IDoItFast.Go()
{
}

void IDoItSlow.Go()
{
}
}

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.

Why explicit interface implementation works that way?

The other answers do not correctly identify the C# feature that you have stumbled upon.

You have discovered a somewhat confusing feature of C# called "interface re-implementation". The rule is that when a derived class specifically re-states an interface that is already implemented by the base class, then the compiler starts over and re-does the interface mapping from scratch.

If that happens then methods of more derived types are given precedence over methods of less derived types because we assume that the developer who is developing the more derived type has a better implementation than the developer who developed the base class version. After all, if the derived version was worse, the developer would not have implemented it!

This rule allows you to decide whether you want a derived class to replace a base class interface mapping or not, because sometimes you want to, and sometimes you don't.

See my 2011 article about this feature for more details:

https://blogs.msdn.microsoft.com/ericlippert/2011/12/08/so-many-interfaces-part-two/

You might also find this answer helpful:

Abstract base classes that implement an interface

For the section of the specification that describes this language feature, see

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/interfaces#interface-re-implementation



Related Topics



Leave a reply



Submit