views:

211

answers:

3

I have found that my WCF services work normally when the data types involved doesn't have the [DataContract], but the [Serializable] instead.

But all the WCF tutorials shows the first one instead of the latter. Why?

+4  A: 

DataContractAttribute gives you more control over what gets sent over the wire, so you can opt to only send the necessary fields of a given entity. Serializable uses platform serialization, which assumes .NET and the same (or similar) versions of the types on both ends of the wire- it (usually) serializes all the private members, state, etc. DCS is intended for a lightweight XML-ish representation that you can have some control over, and XmlSerializer is for an XML format that you can have very fine control over (attribute data, etc).

nitzmahone
Actually the XML serializer gives you more options as to how your data would be represented going across the wire. The big advantage of the Data Contract serializer is speed, but it comes at the price of flexability.
James Bender
Actually DataContract gives you almost no control over the wire format. By implementing ISerializable, you have about as much control over serialization as you do with DataContract. But using XmlSerializer (which I can't really tell from the OP's question) gives far more control. But as Doug mentioned, DataContract is tons faster.
Josh Einstein
+4  A: 

One advantage is that the DataContract serializer is much quicker than the old XmlSerializer.

Edit: The examples would show the [DataContract] attribute because it is the one that is designed for the DataContractSerializer that WCF uses.

Doug Ferguson
That's the primary benefit. You don't get the flexability of the XML serializer, but 99% of the time what the data contract serializer gives you is good enough.
James Bender
To be clear, I don't know if Jader is even asking about XmlSerializer. A type can be marked [Serializable] without using the XmlSerializer format.
Josh Einstein
Josh: True, but if it is marked Serializable WCF will use the XML serializer unless you alter that with a custom behavior.
James Bender
+1  A: 

It's not enough to mark the class with [DataContract], you have to decorate the fields you want to be serialized with [DataMember] as well.

The Data Contract is an "opt in" model of serialization, where the XML serialzier is "opt out."

James Bender