Mike
Mike

Reputation: 6050

Serializable vs Data Contract vs Nothing at all in a WCF Service

I will use the Starter Example given when you create a WCF Service

[DataContract]
public class CompositeType
{
    bool boolValue = true;
    string stringValue = "Hello ";

    [DataMember]
    public bool BoolValue
    {
        get { return boolValue; }
        set { boolValue = value; }
    }

    [DataMember] 
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}

When I use DataContract everything is ok.

When I use Serializable, the actual variables, whether private or public are visualable to the host and not the Properties. If I use NonSerialized it does hide the variable but it doesn't get passed either. I get that, and I think I get why the properties are not passed because there is nothing to serialize? Is that correct?

[Serializable]
public class CompositeType
{
    [NonSerialized]
    bool boolValue = true;
    [NonSerialized]
    string stringValue = "Hello ";


    public bool BoolValue
    {
        get { return boolValue; }
        set { boolValue = value; }
    }


    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}

If I do not supply any attributes, the class gets returned as expected, and this I do not understand?

I am tasked with taking existing business objects and working with them through WCF? It looks like my best option is to leave them alone instead of adding a DataContract attribute. Why is that?

Upvotes: 2

Views: 2869

Answers (1)

Jay
Jay

Reputation: 57979

The [DataContract] attribute is optional.

Why ever use it, then? It lets you control what and how your data is serialized -- for example, which properties are to be included & excluded.

If you can get by without it, that is fine, but you may soon find that you need greater control over what and how data gets sent over the wire.

Upvotes: 3

Related Questions