Question

I need to implement a interface in a class returned by WCF service. How can i do that and keep the data returned by the service?

I have try this:

public class ClientDerived: Client, ImyInteface
{
  public string myInterfaceMethod()
  {
    return "MyInterface Implemented";
  }

}

And then use it like this:

ClientDerived myClient= new ClientDerived();
myClient = (ClientDerived) myService.GetClient();

But i get compiled error when casting my base class to derived class type. So my question remains: How can i implement a new interface on a class returned by wcf and keep his data? Thank you!

Was it helpful?

Solution

You cannot downcast a class to add functionality. It's just not possible in C#. If all you have is a generic Animal, you cannot downcast it to Cat just because you want it to meow.

You should, however, be able to add the interface to the proxy class that has been automatically generated for you by the WCF framework, i.e., to add ImyInterface directly to Client. Since the automatically generated classes are partial by default, you can just extend them:

public partial class Client : IMyInterface
{
    public string myInterfaceMethod()
    {
        return "MyInterface Implemented";
    }
}

Note: The proxy class is usually in a subnamespace of your project namespace (e.g. MyProjectNamespace.MyRemoteService), so be sure to put your extensions in the same namespace. Check the Object Browser (Ctrl+Alt+J) if you don't know the namespace.

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