10 February 2013

Interface implementation types

Interface can be implemented in 2 ways.

  1. Implicit interface implementation

    In implicit interface implementation, interface name will not be mentioned with the method names while implementing them

  2. Explicit interface implementation

    Interfaces will be implemented explicitly by a class when it is implementing more than one interface having the same method signature.

Implicit interface implementation

In implicit interface implementation, interface name will not be mentioned with the method names while implementing them. Let's consider an example:

public interface InterfaceExample
 {
   void Method1(int parameter1, string parameter2);
 }
Now consider a class implementing the InterfaceExample interface.
public class ClassExample : InterfaceExample
{
 public void Method1(int parameter1, string parameter2)
  {
    Console.WriteLine("Implementation of Method1 
                      of InterfaceExample"
);
  }
}
Let's see the usage of the class implementing an interface in implicit manner.
public class Program
{
  static void Main(string[] args)
  {
    ClassExample instance = new ClassExample();
    instance.Method1(2, "parameter");
    Console.ReadLine();
  }
}
Since the class implemented the interface implicitly, we invokde the Method1() using the variable of class type. Hence the below code is possible.
ClassExample instance = new ClassExample();
instance.Method1(2, "parameter");

No comments:

Post a Comment