4

I have two classes...

[Serializable]
[DataContract]
public class A
{
    [DataMember]
    public string _a                                   { get; set; }
    [DataMember]
    public bool _b                                     { get; set; }
}

[Serializable]
public class B : A
{
    [NonSerialized]
    [XmlIgnore] 
    private C _c;
}

... and I have a WCF service:

public interface IClient
{

    [ServiceKnownType(typeof(A))]
    [OperationContract(IsOneWay = true)]
    void Somefunction(List<A> listofA);
}

I need to send a list of A to the client, but I only have a list of B. I don't care about the "_c" field. I would've thought this is as simple as:

List<A> listofA = new List<A>();

foreach (B instanceofb in somestore.Values)
{
    listofA.Add((A)instanceofb);
}

Client.Somefunction(listofA);

But the derived type of the object is stored within the base type instance in the list. WCF seems to try to deserialise and fail because C is not serializable (even though I've marked it as ignored). I get no response on the client side, and the server side method just falls through.

But I can create and send (and receive on the client) type A though:

List<A> listofA = new List<A>() { new A() };
Client.Somefunction(listofA);

Is there any way short of the cringeworthy (which works):

public A Convert(B _instanceofb)
{
  A _instanceofA = new A();
  A._a = _instanceofb._a;
  A._b = _instanceofb._b;
  return A;
}

and ..

List<A> listofA = new List<A>();

foreach (B instanceofb in somestore.Values)
{
    listofA.Add(Convert(instanceofb));
}

Client.Somefunction(listofA);
ornah
  • 41
  • 2
  • Note to editors - rather than correct the question, please add an answer with corrected code if you think the snippets provided are wrong. – Abizern Sep 13 '11 at 08:22

1 Answers1

1

If your objects are instances of B they will always be serialized as instances of B - that is the point of serialization. If you want to ignore _c try this:

[DataContract]
public class B : A
{
    private C _c;
}

If class is marked with DataContract only properties / fields marked with DataMember are serialized - I'm not sure how Serializable works together with parent using DataContract.

You must also use this to tell service and client that B can be used:

public interface IClient
{
    [ServiceKnownType(typeof(B))]
    [OperationContract(IsOneWay = true)]
    void Somefunction(List<A> listofA);
}

If you want to send only A instances you must create A instances not B instances - in your scenario it really means converting.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Hi, maybe you can help here ?http://stackoverflow.com/questions/42294978/lack-of-sent-field-from-sublcass-in-wcf-trying-to-gain-polymorphism?noredirect=1#comment71758889_42294978 –  Feb 17 '17 at 21:49