WCF Opt-In Vs. Opt-Out: Day 8

In this article we will discuss two different approaches i.e. Opt-In and Opt-Out used by DataContractSerializer and XMLSerializer. We will also see the difference between DataContractSerializer and XMLSerializer.

This is the Day 8 article. If you have not read the previous articles, please go through the following articles:
  1. Day 1 - WCF Introduction and Contracts
  2. Day 2 - WCF Fault Contracts
  3. Day 3 - WCF Message Exchange Patterns
  4. Day 4 - WCF DataContract
  5. Day 5 - WCF Difference between service application and service library
  6. Day 6 - WCF Serialization Part 1
  7. Day 7 - WCF Serialization Part 2

Introduction

 
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.
 

Opt-Out Approach

 
In this approach, members are assumed to be serialized except we mention it as NonSerialized. XMLSerializer uses this approach.
 
Opt-Out 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.
 

Opt-In Approach

 
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.
 
Opt-In Approach 
 
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.
 
Open-AuthorServiceLibrary.xsd-file.jpg 
 
Check the result in the Notepad file. In this file you will see only FirstName and LastName. The Article member is not serialized.
 
notepad-AuthorServiceLibrary.xsd-file.jpg 
 
DataContractSerializer
 
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
 
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.
 

Conclusion

 
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.