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?
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.
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.
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.
No, the DataContractAttribute is not required - WCF will infer serialization rules.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With