20.16. Serializing Objects Using the BinaryFormatter

You can use the BinaryFormatter type to illustrate how easy it is to persist an instance of the JamesBondCar to a physical file. Again, the two key methods of the BinaryFormatter type to be aware of are Serialize() and Deserialize():

  • Serialize(): Persists an object graph to a specified stream as a sequence of bytes.

  • Deserialize(): Converts a persisted sequence of bytes to an object graph.

Assume you have created an instance of JamesBondCar, modified some state data, and want to persist your spy mobile into a *.dat file. Begin by creating the *.dat file itself. You can achieve this by creating an instance of the System.IO.FileStream type. At this point, you can create an instance of the BinaryFormatter ...

Get Pro C# 2010 and the .NET 4 Platform, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.