Monday, December 6, 2010

Difference between Implicit and Explicit Interface

There are 4 basic difference between Implicit and Explicit interface. To understand all four of them see the below example first:

There is a class C1 which implements two interfaces I1 and I2. and Both the class have method with same name i.e. sum().

public class C1 : I1, I2
{
//Explicit Implementation of interface
void I2.sum()
{
}

//Implicit Implementation of interface
public void sum()
{
}
}

public interface I1
{
void sum();
}
public interface I2
{
void sum();
}

The Interface I1 is implemented implicitly and I2 is explicitly. Below are the difference based on above example.

1) In Implicit implementation, no need to specify Interface name with its method.
e.g. public void sum() { }
Where as in Explicit implementation, you need to specify Interface name with its method
e.g. void I2.sum() { }

2) In implicit, access specifier is required with method name and it must be public, even protected will not work.
Where as in Explicit, no access specifier will be required.

3) You can not make virtual method in explicit implemention and same will work in implicit implemention.

4) You can not make abstract method in explicit implemention and same will work in implicit implemention.

Practical Example

Now you wonder, by considering above scenario, what is the use of these two implementation because only Implicit implementation will also work for all type of method then why these two has been introduced by Microsoft. or what should be the practical scenario where we need to use either Implicit or Explicit.

Suppose you need to implement 2 interface and both interface will have method with same name. At that time you can not create one method in your class for both interfaces, rather you must implement one interface Implicit and one Explicit (or both Explicit) for showing two different method in your class. (Check above example).

Hiding Interface Details:

If you implement interface explicitly then it will not show in class Intellisense list. So, if you want to hide your method name to display when creating object of class then you need to go for Explicit interface implementation and in this case you need to create object of your interface to know the method name.

E.g.: In our above example if I want to invoke method of I2 interface:
I2 obj = new C1();
obj.sum();

NOTE: for more please click http://developerssolutions.wordpress.com/2010/07/22/difference-between-implicit-and-explicit-interface/

No comments:

Split the String values with a special character in MS Flow to convert this into Array

 Many times we have a requirement to prepare the Mailing address for some of the documents, suppose there are Address Line1, Address Line2, ...