Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

IDeserializationCallback

It is helpful to think of deserialization as a special form of constructor call, since the end result is a valid object reference. While the [NonSerialized] attribute is useful for controlling which data is stored in the serialized form of the object or sent over the wire on a remoting call, the problem is that the fields marked with [NonSerialized] are not assigned meaningful values when the constructor (i.e., the deserialization process) finishes executing. This can result in class invariants being violated, such as the implicit in the preceding sample, in which Age is intended to store the Person’s age based on the DateOfBirth.

One possible solution to this problem is the IDeserializationCallback interface. Implementing this interface on your type indicates to the runtime that you wish to participate in the deserialization process. This interface contains a single method, OnDeserialization, which the runtime invokes after it has finished constructing your object, but before it returns the fully constructed instance to the client. This method gives you a chance to perform whatever fixups you need to inside the object, and is a way to ensure that class invariants are preserved before clients can access the instance.

Using our sample Person class, the IDeserializationCallback interface implementation might look like this:

[Serializable] public sealed class Person : IDeserializationCallback { public string Name; public DateTime DateOfBirth; [NonSerialized] public ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# in a Nutshell

C# in a Nutshell

Ben Albahari, Ted Neward, Peter Drayton
C# 7.0 in a Nutshell

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard

Publisher Resources

ISBN: 0596005261Catalog PageErrata