Serialization

When an object is streamed to disk, its various member data must be serialized -- that is, written out to the stream as a series of bytes. The object will also be serialized when stored in a database or when marshaled across a context, app domain, process, or machine boundary.

The CLR provides support for serializing an object-graph -- an object and all the member data of that object. As noted in Chapter 19, by default, types are not serialized. To serialize an object, you must explicitly mark it with the [Serializable] attribute.

In either case, the CLR will do the work of serializing your object for you. Because the CLR knows how to serialize all the primitive types, if your object consists of nothing but primitive types (all your member data consists of integers, longs, strings, etc.), you’re all set. If your object consists of other user-defined types (classes), you must ensure that these types are also serializable. The CLR will try to serialize each object contained by your object (and all their contained objects as well), but these objects themselves must either be primitive types or they must be serializable.

This was also evident in Chapter 19 when you marshaled a Shape object that contained a Point object as member data. The Point object in turn consisted of primitive data. In order to serialize (and thus marshal) the Shape object, its constituent member, the Point object, also had to be marked as serializable.

Tip

When an object is marshaled, either by ...

Get Programming C#, Second 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.