Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializable and DataContract (not versus?)

I am reading some code in my new project and found out the ex-developer was using Serializable and DataContract together.

[Serializable]

and

[DataContract(Namespace="Some.Name.Space", IsReference = true)]

I assume WCF will ignore Serializable when there is a DataContract attribute. Is this a correct assumption? If not, what are the benefits to use both at the same time?

like image 805
tonyjy Avatar asked Nov 22 '10 19:11

tonyjy


People also ask

What is Datacontract and DataMember?

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.

What is a Datacontract?

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts.

What is the use of Datacontract?

It is used to get or set the order of serialization and deserialization of a member. It instructs the serialization engine that member must be present while reading or deserializing. It gets or sets the DataMember name. It will specify whether the default value to be serialized.

Is Datacontract mandatory in WCF?

No, the DataContractAttribute is not required - WCF will infer serialization rules.


1 Answers

Yes, [Serializable] is ignored if [DataContract] is present. This may be useful to e.g. create a type that will have one serialization projection for WCF, and another projection for .NET Remoting (if it is used alongside WCF for legacy reasons).

UPDATE: I just ran into a situation in my own code where both [DataContract] and [Serializable] were necessary. Suppose you have a class with a bunch of auto-generated properties (e.g. public int Foo {get; set;}) that you want to use both in ASP.NET ViewState and in an ASP.NET Web API JSON endpoint (which uses either the Newtonsoft JSON serializer or the DataContractSerializer). For ViewState to work, you need the class to be [Serializable]. However, this breaks JSON serialization, causing JSON like {"_k_BackingField123":456} instead of {"Foo":456}, because in the [Serializable] model the auto-generated property backing fields get serialized instead of the properties themselves. However, if you also add [DataContract] to the type (and [DataMember] to its properties), both the ViewState and the JSON scenarios work perfectly.

like image 82
Eugene Osovetsky Avatar answered Oct 03 '22 23:10

Eugene Osovetsky