Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using DataContractAttribute over SerializableAttribute?

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?

like image 206
Jader Dias Avatar asked Dec 16 '09 01:12

Jader Dias


People also ask

What is Datacontractattribute?

[DataContract] attribute specifies the data, which is to serialize (in short conversion of structured data into some format like Binary, XML etc.) and deserialize(opposite of serialization) in order to exchange between the client and the Service.

What is data contract and data member in C#?

DataContact. A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember. Creating a basic DataContract and DataMember.

What is serialization in WCF?

Windows Communication Foundation (WCF) uses the DataContractSerializer as its default serialization engine to convert data into XML and to convert XML back into data. The DataContractSerializer is designed to serialize data contract types.

What is data contract in MVC?

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract.


3 Answers

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).

like image 89
nitzmahone Avatar answered Oct 17 '22 01:10

nitzmahone


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."

like image 29
James Bender Avatar answered Oct 17 '22 01:10

James Bender


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.

like image 8
Doug Ferguson Avatar answered Oct 17 '22 01:10

Doug Ferguson