tags:

views:

396

answers:

2

I am working with WCF .NET 3.5 SP1 and have read that one does NOT have to decorate their Entities/Collections with such things as [DataMember], [DataConract], and/or [Serializable]? What is the best way to go? What have you all encountered?

I am on 3.5 SP1.

+4  A: 

See Using Data Contracts.

New complex types that you create must have a data contract defined for them to be serializable. By default, the DataContractSerializer infers the data contract and serializes all publicly visible types. All public read/write properties and fields of the type are serialized. You can opt out members from serialization by using the IgnoreDataMemberAttribute. You can also explicitly create a data contract by using DataContractAttribute and DataMemberAttribute attributes. This is normally done by applying the DataContractAttribute attribute to the type. This attribute can be applied to classes, structures, and enumerations. The DataMemberAttribute attribute must then be applied to each member of the data contract type to indicate that it is a data member, that is, it should be serialized. For more information, see Serializable Types.

Like @Terry said, it's probably better to proactively declare which properties you want to expose. This way you could future proof your code from unintentionally exposing fields when the base class adds a public property in the future.

eed3si9n
Thanks for your reply - so what are negatives w/ just implementing [Serializable] on top of each class? That seems to do it, no? I read in a recent book that [DataMember] and [DataContract] decoration is not needed anymore - its redundant w/ SP1.
See http://www.danrigsby.com/blog/index.php/2008/03/07/xmlserializer-vs-datacontractserializer-serialization-in-wcf/ for the difference between XmlSerializer and DataContractSerializer. You can still get it to work without those attributes ("By default, the DataContractSerializer infers the data contract and serializes all publicly visible types."), but it's better to be explicit is what we are saying.
eed3si9n
+1  A: 

I'm of the opinion that it won't hurt to proactively express you intent to use the class as a DataContract. I would guess that a class that isn't serializable still won't be useful as a DataContract in SP1... :)

Terry Donaghe
+1 - yes, be as explicit as possible - it won't hurt, and it's much clearer what your intent is.
marc_s