HI WELCOME TO SIRIS

Explicit Interface Implementation

Leave a Comment


How to implement the void Method() of the interface in the following case ?

class B 
{
   public void Method() 
   {
       // some code here
       //...
   }
}

interface
 I 

{
   void Method();
}

class D : B, I 
{
   // how to implement the void Method() of the interface
   // public void I.Method() { ... }


To implement void Method, we use explicit interface implementation technique as shown below.

using System;
namespace SampleConsole
{
class Program
{
   static void Main()
   {
      //To Call Class B Method
      D d = new D();
      d.Method();

      //To Call the Interface Method
      I i = new D();
      i.Method();

      //Another way to call Interface method
      ((I)d).Method();
   }
}
class B
{

   public void Method()
   {
      Console.WriteLine("Void Method - B");
   }
}
interface I
{
   void Method();
}
class D : B, I
{
   void I.Method()
   {
      Console.WriteLine("Void Method - I");
   }

}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.