Why implement interface explicitly?

C#Interface

C# Problem Overview


So, what exactly is a good use case for implementing an interface explicitly?

Is it only so that people using the class don't have to look at all those methods/properties in intellisense?

C# Solutions


Solution 1 - C#

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()
	{
	}
}

Solution 2 - C#

It's useful to hide the non-preferred member. For instance, if you implement both IComparable<T> and IComparable it is usually nicer to hide the IComparable overload to not give people the impression that you can compare objects of different types. Similarly, some interfaces are not CLS-compliant, like IConvertible, so if you don't explicitly implement the interface, end users of languages that require CLS compliance cannot use your object. (Which would be very disastrous if the BCL implementers did not hide the IConvertible members of the primitives :))

Another interesting note is that normally using such a construct means that struct that explicitly implement an interface can only invoke them by boxing to the interface type. You can get around this by using generic constraints::

void SomeMethod<T>(T obj) where T:IConvertible

Will not box an int when you pass one to it.

Solution 3 - C#

Some additional reasons to implement an interface explicitly:

backwards compatibility: In case the ICloneable interface changes, implementing method class members don't have to change their method signatures.

cleaner code: there will be a compiler error if the Clone method is removed from ICloneable, however if you implement the method implicitly you can end up with unused 'orphaned' public methods

strong typing: To illustrate supercat's story with an example, this would be my preferred sample code, implementing ICloneable explicitly allows Clone() to be strongly typed when you call it directly as a MyObject instance member:

public class MyObject : ICloneable
{
  public MyObject Clone()
  {
    // my cloning logic;  
  }

  object ICloneable.Clone()
  {
    return this.Clone();
  }
}

Solution 4 - C#

Another useful technique is to have a function's public implementation of a method return a value which is more specific than specified in an interface.

For example, an object can implement ICloneable, but still have its publicly-visible Clone method return its own type.

Likewise, an IAutomobileFactory might have a Manufacture method which returns an Automobile, but a FordExplorerFactory, which implements IAutomobileFactory, might have its Manufacture method return a FordExplorer (which derives from Automobile). Code which knows that it has a FordExplorerFactory could use FordExplorer-specific properties on an object returned by a FordExplorerFactory without having to typecast, while code which merely knew that it had some type of IAutomobileFactory would simply deal with its return as an Automobile.

Solution 5 - C#

It's also useful when you have two interfaces with the same member name and signature, but want to change the behavior of it depending how it's used. (I don't recommend writing code like this):

interface Cat
{
    string Name {get;}
}

interface Dog
{
    string Name{get;}
}

public class Animal : Cat, Dog
{
    string Cat.Name
    {
        get
        {
            return "Cat";
        }
    }

    string Dog.Name
    {
        get
        {
            return "Dog";
        }
    }
}
static void Main(string[] args)
{
    Animal animal = new Animal();
    Cat cat = animal; //Note the use of the same instance of Animal. All we are doing is picking which interface implementation we want to use.
    Dog dog = animal;
    Console.WriteLine(cat.Name); //Prints Cat
    Console.WriteLine(dog.Name); //Prints Dog
}

Solution 6 - C#

It can keep the public interface cleaner to explicitly implement an interface, i.e. your File class might implement IDisposable explicitly and provide a public method Close() which might make more sense to a consumer than Dispose().

F# only offers explicit interface implementation so you always have to cast to the particular interface to access its functionality, which makes for a very explicit (no pun intended) use of the interface.

Solution 7 - C#

If you have an internal interface and you don't want to implement the members on your class publicly, you would implement them explicitly. Implicit implementations are required to be public.

Solution 8 - C#

Another reason for explicit implementation is for maintainability.

When a class gets "busy"--yes it happens, we don't all have the luxury of refactoring other team members' code--then having an explicit implementation makes it clear that a method is in there to satisfy an interface contract.

So it improves the code's "readability".

Solution 9 - C#

A different example is given by System.Collections.Immutable, in which the authors opted to use the technique to preserve a familiar API for collection types while scraping away the parts of the interface that carry no meaning for their new types.

Concretely, ImmutableList<T> implements IList<T> and thus ICollection<T> (in order to allow ImmutableList<T> to be used more easily with legacy code), yet void ICollection<T>.Add(T item) makes no sense for an ImmutableList<T>: since adding an element to an immutable list must not change the existing list, ImmutableList<T> also derives from IImmutableList<T> whose IImmutableList<T> Add(T item) can be used for immutable lists.

Thus in the case of Add, the implementations in ImmutableList<T> end up looking as follows:

public ImmutableList<T> Add(T item)
{
    // Create a new list with the added item
}

IImmutableList<T> IImmutableList<T>.Add(T value) => this.Add(value);

void ICollection<T>.Add(T item) => throw new NotSupportedException();

int IList.Add(object value) => throw new NotSupportedException();

Solution 10 - C#

This is how we can create Explicit Interface: If we have 2 interface and both the interface have the same method and a single class inherit these 2 interfaces so when we call one interface method the compiler got confused which method to be called, so we can manage this problem using Explicit Interface. Here is one example i have given below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace oops3
{
    interface I5
    {
        void getdata();    
    }
    interface I6
    {
        void getdata();    
    }

    class MyClass:I5,I6
    {
        void I5.getdata()
        {
           Console.WriteLine("I5 getdata called");
        }
        void I6.getdata()
        {
            Console.WriteLine("I6 getdata called");
        }
        static void Main(string[] args)
        {
            MyClass obj = new MyClass();
            ((I5)obj).getdata();                     

            Console.ReadLine();    
        }
    }
}

Solution 11 - C#

In case of explicitly defined interfaces, all methods are automatically private, you can't give access modifier public to them. Suppose:

interface Iphone{
  
   void Money();

}

interface Ipen{

   void Price();
}


class Demo : Iphone, Ipen{

  void Iphone.Money(){    //it is private you can't give public               

      Console.WriteLine("You have no money");
  }

  void Ipen.Price(){    //it is private you can't give public

      Console.WriteLine("You have to paid 3$");
  }

}


// So you have to cast to call the method


    class Program
    {
        static void Main(string[] args)
        {
            Demo d = new Demo();

            Iphone i1 = (Iphone)d;

            i1.Money();

            ((Ipen)i1).Price();

            Console.ReadKey();
        }
    }

  // You can't call methods by direct class object

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaster MoralityView Question on Stackoverflow
Solution 1 - C#IainView Answer on Stackoverflow
Solution 2 - C#Michael BView Answer on Stackoverflow
Solution 3 - C#Wiebe TijsmaView Answer on Stackoverflow
Solution 4 - C#supercatView Answer on Stackoverflow
Solution 5 - C#vcsjonesView Answer on Stackoverflow
Solution 6 - C#BrokenGlassView Answer on Stackoverflow
Solution 7 - C#Mike DourView Answer on Stackoverflow
Solution 8 - C#h bobView Answer on Stackoverflow
Solution 9 - C#fugledeView Answer on Stackoverflow
Solution 10 - C#Debendra DashView Answer on Stackoverflow
Solution 11 - C#Md ShahriarView Answer on Stackoverflow