Thursday, July 31, 2008

Difference between Implicit and Explicit implementation of an Interface

Difference between Implicit and Explicit implementation of an Interface

The Scenario:

While doing an API for a project, a colleague of mine ask me about the difference between implicitly and explicitly implementing an interface in C#. In all of the code (in our API), I did an explicit implementation of the interface with the sole purpose for the developers to use the API to code through interface. By doing this, it would promote a loosely coupled implementation between the client code and the API. Here is an example that I used to help me explain the benefit of doing this.

The Interface:
interface ISample
{
void invokeMe(string data);
}


Implicit implementation of the interface:
public class ImplicitClass : ISample
{

#region ISample Members

public void invokeMe(string data)
{
Console.WriteLine(data);
}

#endregion
}


Explicit implementation of the interface:
public class ExplicitClass : ISample
{

#region ISample Members

void ISample.invokeMe(string data)
{
Console.WriteLine(data);
}

#endregion
}


The Client Code:
static void Main(string[] args)
{
// using Implicit implementation
ISample isam;
isam = new ImplicitClass();
isam.invokeMe("Hello implicit world by Interface!");


// using Explicit implementation
ISample isam1;
isam1 = new ExplicitClass();
isam1.invokeMe("Hello explicit world by Interface!");


// using the concrete class on an implicitly implemented class
ImplicitClass imp = new ImplicitClass();
imp.invokeMe("Hello world by the implicit concrete class!");


// using the concrete class on an explicitly implemented class
ExplicitClass exp = new ExplicitClass();
// This code here would not even compile,
// the class could not access the implemented method.
exp.invokeMe("Hello world by the explicit concrete class!");


Console.ReadLine();


}


Summary:

Using implicit implemetation could not force any client code to implement a program-by-interface because as you could see, implemented method can be invoked directly in the concrete class. By using explicit implmentation the client code must program-by-interface (access through interface) to invoke the method.


You might be asking why to program-by-interface? Well, the answer is to promote a loosely coupled implementation. This technique allow server developers to enforce separation of the interface from the implementation.

Sunday, July 20, 2008

My First Blog

Hi this is my first blog, I would like to do some blogging, since I have ample time now to write stuff that makes me ‘Aha!’. My blog would mainly be of a learning process (things that I’ve learned from day-to-day), it might be a newbie topic, as long as it makes me ’Aha!’, it’s gonna be here.

Hope you'll find my blog posts interesting and learn new things here.

We should never stop learning.