Object Serialization in C#

Object serialization is a great way to store your program's data to disk, allowing you to restore the object's state at a later time.  You can serialize custom objects that your app uses, such as user settings and logs/reports, and simply deserialize them whenever you need to retrieve the data stored.

The class below shows the code required for serialization.

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

    public class Serialization {
        public static void SerializeToFile(object obj, string path) {
            BinaryFormatter bf = new BinaryFormatter();
            using (Stream st = File.Create(path)) {
                bf.Serialize(st, obj);
            }
        }
        public static object LoadSerializedFile(string path) {
            BinaryFormatter bf = new BinaryFormatter();
            using (Stream st = File.OpenRead(path)) {
                object o = bf.Deserialize(st);
                return o;
            }
        }
    }

The code below shows how you can use serialization with custom objects.

[Serializable]
public class MyObject {
    public string myString;
    public int myInt;

    public MyObject() {
        this.myString = "Hello.";
        this.myInt = 1;
    }
}
public class WatchMeSerialize {
    public void Serialize() {
        MyObject mo = new MyObject();
        mo.myString = "I'm being serialized.";
        mo.myInt = 5;
        Serialization.SerializeToFile((object)mo, @"C:\myFile.dat");
    }
    public void Deserialize() {
        MyObject mo = (MyObject)Serialization.LoadSerializedFile(@"C:\myFile.dat");
        Console.WriteLine(mo.myString);
        Console.WriteLine(mo.myInt.ToString());
    }
    
}

As you can see from the example above, all you have to do when serializing is place "[Serializable]" above the class that will be serialized, and then cast the object appropriately.