Question

How does a WCF channel (created via ChannelFactory) implement ICommunicationObject, but doesn't expose the Close() method, for example, unless you cast the proxy to ICommunicationObject? Does that make sense?

I got to thinking about that on the way home today and couldn't figure it out in my head. Maybe I'm asking the wrong question? Maybe I'm asking a stupid question? :)

Is it some kind of ninja trick?

Was it helpful?

Solution

This is done via Explicit Interface Implementation.

Suppose you have an interface, like so:

public interface IFoo
{
     void Foo();
}

You can implement this normally:

public class Bar : IFoo
{
     public void Foo() {} // Implicit interface implementation
}

Alternatively, you can implement the interface members explicitly, which requires the cast:

public class Baz : IFoo
{
     void IFoo.Foo() {} // This will require casting the object to IFoo to call
}

This can be very useful at times. For example, it is often done to implement IDisposable in classes where the preferred API would be to call .Close(), for example. By implementing IDisposable explicitly, you "hide" the Dispose() method, but still allow the class instance to be used via a using statement.

OTHER TIPS

The Channel class implements the ICommunicationObject interface explicitly. Here's an example demonstrating the difference between explicit interface implementation and implicit interface implementation:

internal interface IExample
{
    void DoSomething();
}

class ImplicitExample : IExample
{
    public void DoSomething()
    {
        // ...
    }
}

class ExplicitExample : IExample
{
    void IExample.DoSomething()
    {
        // ...
    }
}

class Consumer
{
    void Demo()
    {
        var explicitExample = new ExplicitExample();
        // explicitExample.DoSomething(); <-- won't compile
        ((IExample)explicitExample).DoSomething(); // <-- compiles

        var implicitExample = new ImplicitExample();
        implicitExample.DoSomething(); // <-- compiles
    }
}

Here is a link to the an MSDN article on this subject: http://msdn.microsoft.com/en-us/library/ms173157.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top