Data Contract Attribute And Its Parameters in WCF

Data contract is an agreement between client and Service about the data, which is to be exchanged between them. The important thing to remember is that both of them need to share data contract only rather than the data types for the communication. WCF (Windows Communication Foundation) uses serialization engine to serialize and deserialize the data. [DataContract] attribute specifies the data, which is to serialize (in short conversion of structured data into some format like Binary, XML etc.) and deserialize(opposite of serialization) in order to exchange between the client and the Service. Data Contract attribute can be annotated on a class, Enum or even a structure but not on an interface. 

Example

  1.     [DataContract]  
  2.     public class Student  
  3.     {  
  4.         [DataMember]  
  5.         public int ID;  
  6.         [DataMember]  
  7.         public string Name;  
  8.     }  

[DataContract] attribute parameters 

[DataContract] attribute contains parameters, which are used to specify additonal information about Data Contract.The name of these parameters and their functions are given below.

IsReference

This parameter is of bool type and specifies that whether to preserve the object reference data or not. Its default value is false. To keep object reference data preserve, set its value to true.

Example

  1.     [DataContract(IsReference =true)]  
  2.     public class Student  
  3.     {  
  4.         [DataMember]  
  5.         public int ID;  
  6.         [DataMember]  
  7.         public string Name;  
  8.     }  

Name

This parameter gets or sets the name of Data Contract and is used as type name in XML schema. The default value of this parameter is the name of the class on which it is applied. 

Example

  1.     [DataContract(Name ="StudentInformation")]  
  2.     public class Student  
  3.     {  
  4.         [DataMember]  
  5.         public int ID;  
  6.         [DataMember]  
  7.         public string Name;  
  8.     }  

Namespace

This parameter takes a URL template and is used to specify the namespace for Data Contract. The default value of this parameter comes from CLR namespace.

Example

  1.     [DataContract(Namespace = "http://www.StudentInformationManagement.com")]  
  2.     public class Student  
  3.     {  
  4.         [DataMember]  
  5.         public int ID;  
  6.         [DataMember]  
  7.         public string Name;  
  8.     }   
Data Contract attribute is very useful to define data policy, which is to be exchanged between the client and the Service. In this blog, I have discussed the attribute and its parameter through which you can define the policies. The members of Data Contract can be defined through DataMember attribute as you can see in examples given above. I will talk about DataMember attribute in my next blog.