inforakesha

A fine WordPress.com site

Serialization in WCF

Leave a comment

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.jpg

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.jpg

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s