​

 I  am very confused about the ​​DataContract​​ attribute in WCF. As per my knowledge it is used for serialization user defined type like classes. I write a one class which is expose at client side.



[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; }
}


It is working properly but when I remove ​​DataContract​​ at class level as well as ​​DataMember​​ it is also work properly. I can't understand that if it is working properly so why there is a need of ​​DataContract​​? Can any one tell me what is the actual use of ​​DataContract​​?

My service contract looks like this



[ServiceContract]    
public interface IRestServiceImpl
{
[OperationContract]
Contact XmlData(string id);
}


 

 

 

解答:

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...