Sunday, 18 January 2015

When to use DataContract and DataMember attributes in WCF



[DataContract]
public class Contact
{
    [DataMember]
    public int Roll { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Address { get; set; }

    [DataMember]
    public int Age { get; set; }
}
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:
1)    without [DataContract], you cannot define an XML namespace for your data to live in.
2)    without [DataMember], you cannot serialize non-public properties or fields.
3)    without [DataMember], you cannot define an order of serialization (Order=) and the DCS will serialize all properties alphabetically.
4)    without [DataMember], you cannot define a different name for your property (Name=).
5)    without [DataMember], you cannot define things like IsRequired= or other useful attributes.
6)    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.



2 comments: