serialize an object graph in csharp

To serialize an object graph in C#, you can use the BinaryFormatter class which is available in the System.Runtime.Serialization.Formatters.Binary namespace. The BinaryFormatter class can be used to serialize and deserialize an object graph into binary format.

Here's an example of how to serialize an object graph using BinaryFormatter:

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

// The object graph to be serialized
var graph = new MyObjectGraph();

// Create a BinaryFormatter object
var formatter = new BinaryFormatter();

// Create a FileStream to write the serialized object to a file
using (var stream = new FileStream("data.bin", FileMode.Create))
{
    // Serialize the object graph to the file
    formatter.Serialize(stream, graph);
}
437 chars
16 lines

In the code above, the MyObjectGraph instance is serialized into binary format using the BinaryFormatter.Serialize() method. This method takes two arguments: the first argument is the stream to write the serialized data to (in this case, a FileStream), and the second argument is the object to be serialized.

Deserializing the object graph can be done using code similar to the following:

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

// Create a BinaryFormatter object
var formatter = new BinaryFormatter();

// Create a FileStream to read the serialized object from a file
using (var stream = new FileStream("data.bin", FileMode.Open))
{
    // Deserialize the object graph from the file
    var graph = (MyObjectGraph)formatter.Deserialize(stream);
}
391 chars
13 lines

In the code above, the BinaryFormatter.Deserialize() method is called to deserialize the object graph from the file. This method takes one argument: the stream to read the serialized data from (in this case, a FileStream). The deserialized object is then cast to the correct type, which in this case is MyObjectGraph.

gistlibby LogSnag