Home > Development > Binary Serialization – Controlling it manually

Binary Serialization – Controlling it manually

Hi all, Just a quick post on how to control serialization manually. If you need full control of the process implement ISerializable. In the GetObjectData method add the field / properties ect you want to the dictionary then create a constructor to pull them out again.

using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace ISerializableDemo

    public class Customer : ISerializable
        private readonly string name;
        private readonly string address;

        public Customer(string name, string address)
            this.name = name;
            this.address = address;

        protected Customer(SerializationInfo info, StreamingContext context)
            this.name = info.GetString("Name");
            this.address = info.GetString("Address");

        public string Address
            get { return address; }

        public string Name
            get { return name; }

        public void GetObjectData(SerializationInfo info, StreamingContext context)

    class Program
        static void Main(string[] args)
            Customer c1 = new Customer("Blair","25 Test Avenue Australia");
            MemoryStream stream = new MemoryStream();

            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, c1);

            stream.Position = 0;
            Customer c2 = (Customer) formatter.Deserialize(stream);

            Console.WriteLine(c2.Name + " - " + c2.Address);

Hope this helps.
Categories: Development Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: