In this article we will discuss two approaches i.e. Opt-In and Opt-Out used by DataContractSerializer and XMLSerializer. We will also see the difference between DataContractSerializer and XMLSerializer.
In this approach, members are assumed to be serialized except we mention it as NonSerialized. XMLSerializer uses this approach.
In the above example, we set the Serializable attribute to the Author class. In other words all class members are going to be serialized but suppose we do not want to serialize the article member then set the NonSerialized attribute on article member. In this case only the firstname and lastname are serialized.
In this approach we need to specify each member, which we want to serialize. For example we want to serialize the firstname and lastname, not an article member then we need to set the DataMember attribute to the firstname and lastname.
In the above code snippet you can see that we are not applying the DataMember attribute to the Article member. That’s why this member is not serialized.
Now check this with svcutil.exe from the command prompt. It will generate an AuthorServiceLibrary.xsd file.
Open the AuthorServiceLibrary.xsd file in the Notepad.
Check the result in the Notepad file. In this file you will see only FirstName and LastName. The Article member is not serialized.
DataContractSerializer uses the Opt-In approach. This approach serializes properties as well as fields. We can serialize protected and private members also. The DataContractSerializer is faster than XMLSerializer because we don’t have full control over serialization.
XMLSerializer uses The Opt-Out approach. This approach serializes properties only and it must be a public. It cannot understand the DataContractSerializer attribute. It will not serialize unless we apply the serializable attribute.
The DataContractSerializer is always able to serialize to XML, but it is for very small and simple XML. It focuses on speed instead of on being comprehensive. And XMLSerializer is used for comprehensive XML schemas.