serialize and object graph in csharp

To serialize an object graph in C#, two common approaches are using BinaryFormatter or XmlSerializer. Here are examples of both:

Using BinaryFormatter:

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

// Define a class to be serialized
[Serializable]
public class MyClass
{
    public int IntProperty { get; set; }
    public string StringProperty { get; set; }
}

// Serialize an instance of MyClass to a file
MyClass myObject = new MyClass { IntProperty = 123, StringProperty = "hello" };
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = File.Create("myObject.bin"))
{
    formatter.Serialize(stream, myObject);
}
530 chars
20 lines

Using XmlSerializer:

main.cs
using System;
using System.IO;
using System.Xml.Serialization;

// Define a class to be serialized
public class MyClass
{
    public int IntProperty { get; set; }
    public string StringProperty { get; set; }
}

// Serialize an instance of MyClass to an XML file
MyClass myObject = new MyClass { IntProperty = 123, StringProperty = "hello" };
XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
using (FileStream stream = File.Create("myObject.xml"))
{
    serializer.Serialize(stream, myObject);
}
511 chars
19 lines

In both cases, the serialized output will be saved to a file, which can later be deserialized to re-create the original object graph.

gistlibby LogSnag