Why we used DataContract serializer in Wcf?

  1. DataContractSerializer is better performance over Xmlserializer. This is because DataContratSerializer explicitly shows the which fields or properties are serialized into XML.
  2. DataContractSerializer can able to serialize types that implements Idictionary whereas XML serializer not.
  3. DataContractSerializer serializes all members which are marked with [DataMember] attribute even if member is marked private. XML serializer serialize only public members.
The DataContractSerializer is used in combination with the DataContractAttribute and DataMemberAttribute classes
namespace DataContractSerializerExample
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.Xml;
    // You must apply a DataContractAttribute or SerializableAttribute
    // to a class to have it serialized by the DataContractSerializer.
    [DataContract(Name = "Customer", Namespace = "http://www.contoso.com")]
    class Person : IExtensibleDataObject
    {
        [DataMember()]
        public string FirstName;
        [DataMember]
        public string LastName;
        [DataMember()]
        public int ID;
        public Person(string newfName, string newLName, int newID)
        {
            FirstName = newfName;
            LastName = newLName;
            ID = newID;
        }
        private ExtensionDataObject extensionData_Value;
        public ExtensionDataObject ExtensionData
        {
            get
            {
                return extensionData_Value;
            }
            set
            {
                extensionData_Value = value;
            }
        }
    }

Comments