which implement interface to use

R

rodchar

hey all,
when i implement my interface i built i get a choice of
1. Implement Inteface
2. Explicitly Implement Interface
can someone please tell what the difference is?
thanks,
rodchar
 
T

Tom Shelton

hey all,
when i implement my interface i built i get a choice of
1. Implement Inteface
2. Explicitly Implement Interface
can someone please tell what the difference is?
thanks,
rodchar

The difference is really about the visibility of the interface methods
based on the type of reference you have. When an interface is
explicitly implemented, it's methds are only visible on the class when
you have a reference of the interface type... Here is a simple example:

using System;

namespace InterfaceTest
{
public static class Program
{
public static void Main()
{
Implementation imp = new Implementation();
imp.Method1();

ExplicitImplementation eimp = new ExplicitImplementation();
eimp.Method1(); // compile error - ISomeInterface is not available!

ISomeInterface ieimp = eimp;
ieimp.Method1();
}

}

internal interface ISomeInterface
{
void Method1();
}

internal class Implementation : ISomeInterface
{

public void Method1()
{
Console.WriteLine ("Method1");
}
}

internal class ExplicitImplementation : ISomeInterface
{
void ISomeInterface.Method1()
{
Console.WriteLine("Explicit Implementation Method1");
}
}
}

The above code does not compile because of the call to Method1 on an
ExplicitImplementation instance. If you were to comment out that line
of code, then the program would compile and run.

This difference may seem strange, but it does have it's uses :) For
instance, one of the main places I make use of this feature, is on
classes that implement IDisposable. Sometimes, you want an Open/Close
type symantics - a Stream class for example - but, you still want your
object to be able to be used in a using block... Using Explicit
Implementation, you can get both:

public class ClosableClass : IDisposable

void IDisposable.Dispose()
{
// CLEAN UP
}

public void Close()
{
((IDisposable) this).Dispose();
}
}

Now clients of this class only see the Close method, but they can stil
use it like:

using (ClosableClass closer = new ClosableClass())
{
// DO WORK
}

Anyway, that's a fairly simplistic example, and I hope it makes the
difference clear.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top