Let us see some of the classes, attributes and interfaces
used in serialization.
SerializableAttribute – Any class that can be serialized should
be marked as a "Serializable" attribute. Generally, all the business
objects or Data Transfer Objects (DTO) are marked as serializable.
NonSerializedAttribute – If a class is marked as Serializable
then all the properties can be serialized. For example, if we have a User
object that has properties like user name, password [not in encrypted format],
role of the user, etc. then such kinds of crucial information can be leaked out
if serialized. We have the NonSerializable attribute that helps us in marking a
property as not serializable.
*ISerializable interface – By implementing this interface it
allows the object to control its own serialization and deserialization. This
feature is new in .NET 3.0. ISerializable interface has a void method called GetObjectData.
Method GetObjectData takes two parameters SerializationInfo and
StreamingContext. Let us see how can we implement this method while using the
ISerializable.GetObjectData( SerializationInfo info, StreamingContext context)
// Instead of serializing this object,
// serialize a SingletonSerializationHelp instead.
// No other values need to be added.
Listing 1 shows the implementation of method GetObjectData.
As we can see from the listing, the SerializationInfo object is set to
MySerializationHelper. The class MySerializationHelper implements an interface
IObjectReference. Listing 2 shows the same.
internal sealed class MyClassSerializationHelper : IObjectReference
//This object has no fields (although it could).
//GetRealObject is called after this object is deserialized.
public Object GetRealObject(StreamingContext context)
// When deserialiing this object, return a reference to
// the Singleton object instead.
Understanding System.Runtime.Serialization namespace
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 class Serializes and deserializes an object to an XML
This attribute is applied to the member of a type. This specifies
that the member is part of a data contract and is serializable by the
Specifies that the field is an enumeration member and
should be serialized.
Serializes and deserializes an instance of a type into an
XML stream or document using a supplied data contract.