Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a WCF proxy implement ICommunicationObject if it's methods aren't visible?

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?

like image 857
Alex Dresko Avatar asked Aug 07 '12 22:08

Alex Dresko


2 Answers

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.

like image 188
Reed Copsey Avatar answered Oct 20 '22 19:10

Reed Copsey


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

like image 42
Dan Avatar answered Oct 20 '22 21:10

Dan