What is explicit interface implementation in C#

Description

We have to do explicit interface implementation when implementing interfaces with collision.

In the following code we have two interfaces. Then have the methods with identical signature. We do the explicit interface implementation by adding interface name in front of the method name.


using System;/*  ww  w . j  a v  a  2  s. co m*/
interface Printable{
   void print();
}

interface Outputable{
   void print();
}
class MyClass: Printable, Outputable{
  public void print(){
     Console.WriteLine("Printable.print");
  }
  void Outputable.print(){
     Console.WriteLine("Outputable.print");
  }
}

class Test
{
    static void Main()
    {
        MyClass cls = new MyClass();

        cls.print();
        ((Outputable)cls).print();

    }
}

From the code above we can see that when calling the explicited interface implementation we have to the cast.

The output:





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor