Vasu Balakrishnan’s Blog

C# Explicit Interface Implementation

leave a comment »

 

C# lets you explicitly implement an interface. When you do that the interface member can be accessed only by using a reference to the interface. I was wondering why do we need this feature.

It turns out when you’ve a class that implements multiple interfaces,  which have some common methods in them and they don’t perform the same function. You can then implement the interface explicitly. Here is an example from MSDN

interface IControl
{
    void Paint();
}
interface ISurface
{
    void Paint();
}

// Implicit Implementation
class SampleClass : IControl, ISurface
{
    // Both ISurface.Paint and IControl.Paint call this method.
    public void Paint()
    {
    }
}

// Explicit Implementation
public class SampleClass : IControl, ISurface
{
    void IControl.Paint()
    {
        System.Console.WriteLine("IControl.Paint");
    }
    void ISurface.Paint()
    {
        System.Console.WriteLine("ISurface.Paint");
    }
}

 

Also explicit interfaces can be used to resolve cases when two interfaces each declare different members of the same name (like a property and a method).

One of the most common reason to explicitly implement an interface, is to hide them from developers as they don’t appear in the publicly visible members.

Advertisements

Written by nbvasu

July 29, 2009 at 10:44 am

Posted in C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: