Home > Development > Binary Serialization

Binary Serialization


Just the facts:

  • Serializes all fields unless otherwise specified
  • Only serializes fields
  • Serializes both private and public fields
  • Requires types be annotated with [Serializable]
  • If fields are not serializable an exception is thrown
  • You can further control serialization and stop fields from being serialized by using [NonSerialized] attribute on the field.
  • Versioning is not great
  • Great from serializing object graphs
  • Very fast

We are going to cover the basics and will add future posts to cover more detailed information.

Here is some code for discussion.

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

namespace BinarySerialization
{

    [Serializable]
    public class Student
    {

        private readonly int id;
        private readonly string name;
        private readonly DateTime birthdate;
        private readonly IList<Course> courses;
       
        [NonSerialized]
        private int age;

        public Student(int id, string name, DateTime birthdate)
        {
            this.id = id;
            this.name = name;
            this.birthdate = birthdate;
            this.age = CalculateAge(birthdate);
            this.courses = new List<Course>();
        }

        private static int CalculateAge(DateTime _birthdate)
        {
            return (DateTime.Now - _birthdate).Days / 365;
        }

        [OnDeserialized]
        public void OnDeserialized(StreamingContext context)
        {
            this.age = CalculateAge(birthdate);
        }

        public int Age
        {
            get { return age; }
        }

        public DateTime Birthdate
        {
            get { return birthdate; }
        }

        public int Id
        {
            get { return id; }
        }

        public string Name
        {
            get { return name; }
        }

        public void AddCourse(Course c)
        {
            this.courses.Add(c);
        }

        public int CoursesTaken
        {
            get
            {
                return this.courses.Count;
            }
        }
    }

    [Serializable]
    public class Course
    {
        private readonly string name;

        public Course(string name)
        {
            this.name = name;
        }

        public string Name
        {
            get { return name; }
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                Student studentToSerialize = new Student(1, "Blair Davidson", new DateTime(1981,6,14));
                studentToSerialize.AddCourse(new Course("Maths"));

                Console.WriteLine("Id: {0}, Name:{1}, Age: {2} Courses Taken: {3}", studentToSerialize.Id,
                                  studentToSerialize.Name, studentToSerialize.Age,
                                  studentToSerialize.CoursesTaken);

                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(memoryStream, studentToSerialize);

                memoryStream.Position = 0;
                Student deSerializedStudent = (Student)formatter.Deserialize(memoryStream);

                Console.WriteLine("Id: {0}, Name:{1}, Age: {2} Courses Taken: {3}", deSerializedStudent.Id,
                                 deSerializedStudent.Name, deSerializedStudent.Age,
                                 deSerializedStudent.CoursesTaken);

            }

            Console.ReadKey();
        }
    }
}

You can also see that age is not serialized as it is a calculated field. We also use the Deserialized event and recalculate the age when we deserialize the object.

I will be covering more shortly.

Blair…

Advertisements
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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: