XmlSerializer was with Microsoft .NET since version 1.0 but with .NET framework version 3.0, Microsoft introduces DataContractSerializer. DataContractSerializer is the default serializer for WCF although we can still use XmlSerializer for serialization in Windows Communication Foundation.
A basic difference between the two Serializers is the approach being used and that is the primary goal of this WCF tutorial. DataContractSerializer uses Opt-In approach as opposite to XmlSerializer.
Opt-In approach says properties that are considered to be part of DataContract must be explicitly marked othewise will be ignore, while Opt-Out means all of the properties will be assumed to be part of the DataContract unless marked explicitly.
Opt-In approach says properties that are considered to be part of DataContract must be explicitly marked othewise will be ignore, while Opt-Out means all of the properties will be assumed to be part of the DataContract unless marked explicitly.
Let’s understand it with the help of a practical example. Following code snippet clearly explains Opt-In approach.
namespace MySchoolService
{
[DataContract]
public class Student
{
{
[DataContract]
public class Student
{
[DataMember]
public string StudentNumber;
public string StudentNumber;
[DataMember]
public string FirstName;
public string FirstName;
[DataMember]
public string LastName;
public string LastName;
public string MarksObtained;
}
[ServiceContract]
}
[ServiceContract]
public interface IStudentService
{
//Service Code Here.
}
}
{
//Service Code Here.
}
}
In above code StudentNumber, FirstName, LastName properties of Student class are explicitly marked with DataMember attribute as oppose to MarksObtained, so MarksObtained will be ignored.
Top Books on Windows Communication Foundation
Below code represents an example of Opt-Out approach.
namespace MySchoolService
{
[Serializable()]
public class Student
{
public string StudentNumber;
public string FirstName;
public string LastName;
{
[Serializable()]
public class Student
{
public string StudentNumber;
public string FirstName;
public string LastName;
[NonSerialized()]
public string marksObtained;
}
public string marksObtained;
}
[ServiceContract]
public interface IStudentService
{
//Service Code Here.
}
}
public interface IStudentService
{
//Service Code Here.
}
}
In above example, we explicitly marked MarksObtained property as [NonSerialized()] attribute, so it will be ignored except the others.
I high appreciate this post. It’s hard to find the good from the bad sometimes but I think you’ve nailed it! would you mind updating your blog with more information?
Outdoor Furniture