15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

[OnSerializing] and [OnSerialized]<br />

The binary engine also supports the [OnSerializing] and [OnSerialized] attributes.<br />

These flag a method for execution before or after serialization. To see how they can<br />

be useful, we’ll define a Team class that contains a generic List of players:<br />

[Serializable] public sealed class Team<br />

{<br />

public string Name;<br />

public List Players = new List();<br />

}<br />

This class serializes and deserializes correctly with the binary formatter but not the<br />

SOAP formatter. This is because of an obscure limitation: the SOAP formatter refuses<br />

to serialize generic types! An easy solution is to convert Players to an array just<br />

prior to serialization, then convert it back to a generic List upon deserialization. To<br />

make this work, we can add another field for storing the array, mark the original<br />

Players field as [NonSerialized], and then write the conversion code in as follows:<br />

[Serializable] public sealed class Team<br />

{<br />

public string Name;<br />

Person[] _playersToSerialize;<br />

[NonSerialized] public List Players = new List();<br />

[OnSerializing]<br />

void OnSerializing (StreamingContext context)<br />

{<br />

_playersToSerialize = Players.ToArray();<br />

}<br />

[OnSerialized]<br />

void OnSerialized (StreamingContext context)<br />

{<br />

_playersToSerialize = null; // Allow it to be freed from memory<br />

}<br />

[OnDeserialized]<br />

void OnDeserialized (StreamingContext context)<br />

{<br />

Players = new List (_playersToSerialize);<br />

}<br />

}<br />

[OptionalField] and Versioning<br />

By default, adding a field breaks compatibility with data that’s already serialized,<br />

unless you attach the [OptionalField] attribute to the new field.<br />

To illustrate, suppose we start with a Person class that has just one field. Let’s call<br />

it Version 1:<br />

632 | Chapter 16: Serialization

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!