Pages

Thursday, December 27, 2007

System.Runtime.Serialization namespace in .NET 3.0

This is a new namespace that has been added in .NET Framework 3.0. It has rich functionality with classes that are used for serializing and deserializing objects. Let us see some of the new classes that are added in this namespace.

1.DataContractAttribute --- This class Serializes and deserializes an object to an XML stream.

2.DataMemberAttribute--- This attribute is applied to the member of a type. This specifies that the member is part of a data contract andis serializable by the DataContractSerializer.

3.EnumMemberAttribute ---- Specifies that the field is an enumeration member and
should be serialized.

4.DataContractSerializer---- Serializes and deserializes an instance of a type into an XML stream or document using a supplied data contract.

Comparing Basic serialization with Custom serialization

Using basic serialization we can have an attribute "Serializable" at the class level. Using basic serialization, it is up to the .NET Framework to take care of the serialization and de-serialization. But the problem with this type of serialization is that we cannot have control over the serialization algorithm. Another major issue with basic serialization is that we have versioning issues like "System.Runtime.Serialization.SerializationException" Possible Version mismatch. But basic serialization is the easiest way for serialization.

On other hand custom serialization gives us more control. As we have seen in listing 1 and 2, we can implement the interface ISerializable which gives us more control over the serialization algorithm. We can also avoid the serialization exceptions with the custom serialization. Apart from these, we have 4 attributes when applied to methods they are called in the process of serialization.

OnDeserializedAttribute – This attribute when put on a method, the method gets fired when the de-serialization is completely done.

OnDeserializingAttribute – When applied on a method this method is called during de-serialization of an object.

OnSerializedAttribute – When applied on a method this method gets fired after the serialization process takes place.

OnSerializingAttribute – When applied on a method this is fired during the serialization process.

We can get maximum control over serialization and deserialization process using the attributes.

No comments: