At this point, we are experts on reading and writing various datatypes to and from streams. However, what we haven't considered is dealing with perhaps the most important datatype, an object. How do you save an object to the stream and load it back such that it is in the same state when it was saved?

One way is to provide explicit save and load methods on your class that take a Stream object as an argument. Within each method, you can explicitly save or load each member field of the class.

There is nothing wrong with this technique; but when dealing with large numbers of classes, it soon becomes painful to add the logic to each of the classes. Why can't we write a generic mechanism to load and save any arbitrary object? After all, ...

Get .NET Programming: A Practical Guide Using C# now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.