Search code examples
c#wcfdatacontract

DataContract for serializing interface subclasses


My situation is something like this : There's a service method that should accept a collection of some interface. The client has several classes implementing that interface. For argument's sake there might be only one, the point is that they only add private members. I don't want the service to know the implementing types in the client. So is there a way for me to create another subclass of that interface in the service that will act as a DataContract in order to properly serialize/deserialize the existing classes I have in my client? Or maybe I need a different solution here?


Solution

  • You can create a base class on your client side, where all of the subclasses that implements that interface will inherit from, and add a KnownTypeAttribute for each one

    [KnownType(typeof(Subclass1))]
    [KnownType(typeof(Subclass2))]
    [DataContract]
    public class BaseClass : ISomeInterface
    {
    
    }