When to use DataContract and DataMember attributes?

Since a lot of programmers were overwhelmed with the [DataContract] and [DataMember] attributes, with .NET 3.5 SP1, Microsoft made the data contract serializer handle all classes – even without any of those attributes – much like the old XML serializer.

So as of .NET 3.5 SP1, you don’t have to add data contract or data member attributes anymore – if you don’t then the data contract serializer will serialize all public properties on your class, just like the XML serializer would.

HOWEVER: by not adding those attributes, you lose a lot of useful capabilities:

  • without [DataContract], you cannot define an XML namespace for your data to live in
  • without [DataMember], you cannot serialize non-public properties or fields
  • without [DataMember], you cannot define an order of serialization (Order=) and the DCS will serialize all properties alphabetically
  • without [DataMember], you cannot define a different name for your property (Name=)
  • without [DataMember], you cannot define things like IsRequired= or other useful attributes
  • without [DataMember], you cannot leave out certain public properties – all public properties will be serialized by the DCS

So for a “quick’n’dirty” solution, leaving away the [DataContract] and [DataMember] attributes will work – but it’s still a good idea to have them on your data classes – just to be more explicit about what you’re doing, and to give yourself access to all those additional features that you don’t get without them…

Leave a Comment