ASP.NET and C# Serialization and Deserialization

In the word of distributed systems it’s often important to pass data in the XML format across networks, XML formats are all text and we need to convert XML file into the string of bites for the transmission over the network. Serialize is conversion of objects into stream of bytes and if we need to revert back to object we deserialize bytes into objects.

BinaryFormatter Properties


AssemblyFormat Formats deserializer with regards to finding and loading assemblies
Binder Formats an object of type SerializationBinder
Context Formats or sets the StreamingContext
FilterLevel Formats the TypeFilterLevel
SurrogateSelector Formats a ISurrogateSelector
TypeFormat Formats the format in which type descriptions are laid

BinaryFormatter Methods are


Deserialize Overloaded. Deserializes
DeserializeMethodResponse Deserializes a response
Equals Determines whether two Object instances are equal
GetHashCode Serves as a hash function for a particular type
GetType Gets the Type
ReferenceEquals Determines whether the specified Object instances are the same instance
Serialize Serializes an object, or graph
ToString Gets a String that represents the current Object
UnsafeDeserialize Deserializes the specified stream
UnsafeDeserializeMethodResponse Deserializes a response to a remote method

Object serialization happens in two distinct steps

  1. Create stream to hold serialized object
  2. With the help of BinaryFormatter call Serialize method to serialize object and then output result to stream. Result is stored as ASCII text with additional bytes added at the start and end of the string.
We need to use following namespaces to implement serialization: System.IO, System.Runtime.Serialization, and System.Runtime.Serialization.Formatters.Binary
string data = "This is in the file.";
FileStream myFileStream = new FileStream("SerializedString.Data", FileMode.Create);
BinaryFormatter myBinaryFormatter = new BinaryFormatter();
myBinaryFormatter.Serialize(myFileStream, data);

Object Deserialization also requires several steps

  1. Create Stream object to read input
  2. Create objects to hold deserialized stream
  3. BinaryFormatter.Deserialize deserialize the object, and cast it to the correct type.
// Open file
FileStream myFileStream = new FileStream("SerializedDate.Data", FileMode.Open);
BinaryFormatter myBinaryFormatter = new BinaryFormatter();
DateTime myDateTime = new DateTime();
myDateTime = (DateTime) myBinaryFormatter.Deserialize(myFileStream);
Console.WriteLine("Day: " + myDateTime.DayOfWeek + ", _
    Time: "
+ previousTime.TimeOfDay.ToString());

In order to set up class to be serializable you need to add attribute called Serializable to the class.
class ShoppingCartItem : IDeserializationCallback {
    public int productId;
    public decimal price;
    public int quantity;
    [NonSerialized] public decimal total;
    <OptionalField()> Public taxable As Boolean

    public ShoppingCartItem(int _myProductID, decimal _myPrice, int _myCuantity)
        productId = _myProductID;
        price = _myPrice;
        quantity = _myCuantity;
        total = price * quantity;
    void IDeserializationCallback.OnDeserialization(Object sender)
        //Calculate the total
        total = price * quantity;

Please note [NonSerialized] attribute for total, the idea behind this attribute is that you don’t need to serialize everything within a class and total can be computed so there is no need to include it into the file. Total will not be initialized when we deserialize object with this attribute. However, we need to include total and hence need to calculate it while deserializing class with the help of IDeserializationCallback.OnDeserialization. In order to preserve objects from version to version we may set new property of the object as optional <OptionalField()>

Serialization comes in two different formats.

Binary format: System.Runtime.Serialization.Formatters.Binary this is most efficient format for .NET Framework and can only be read by .NET Dev. Environments.

SoapFormatter Located in the System.Runtime.Serialization.Formatters.Soap is XML based formatter to send across networks and can be read by any non .NET Dev Environments. Also it is the best way to bypass Firewalls. In order to use SoapFormater you need add System.Runtime.Serialization.Formatters .Soap.dll assembly to your project. XML Serialization has a set of attributes for better interoperability.


SoapAttribute The class member
SoapElement The class
SoapEnum The element
SoapIgnore The property or field
SoapInclude The type