Skip to Main Content
C# in a Nutshell
book

C# in a Nutshell

by Ben Albahari, Ted Neward, Peter Drayton
March 2002
Intermediate to advanced content levelIntermediate to advanced
864 pages
31h 8m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell

[Serializable]

In the preceding examples we assumed for simplicity’s sake that the object graph was serializable, and we focused on how serialization and deserialization occurred. Now let’s spend some time defining what it means for an object or object graph to be serializable, and how to mark your classes and structs as such.

Types that should support being serialized and deserialized by the runtime must be marked with the [Serializable] attribute, as follows:

[Serializable]
public sealed class Person {
  public string Name;
  public int Age;
}

This sets a special serializable bit in the metadata for the type that instructs the runtime to provide serialization and deserialization support. The [Serializable] attribute is not inherited, thus derived types are not automatically serializable. To provide for the serialization of derived types, mark each type as [Serializable].

As we saw earlier in Section 11.4, serializing a type implicitly serializes all members of the type, recursively. This implies that all members of a type must themselves be serializable for the type to successfully serialize. This is true regardless of the accessibility of the members. For example, if you modify the Person class as follows, it will no longer be serializable:

[Serializable]
public sealed class Person {
  public string Name;
  public int Age;
  private Company Employer; // Person no longer Serializable!
}
  
public class Company {...}

Attempting to serialize an instance of Person now results in a SerializationException ...

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# 8.0 in a Nutshell

C# 8.0 in a Nutshell

Joseph Albahari, Eric Johannsen
C# 10 in a Nutshell

C# 10 in a Nutshell

Joseph Albahari
C# in a Nutshell, Second Edition

C# in a Nutshell, Second Edition

Peter Drayton, Ben Albahari, Ted Neward
Code like a Pro in C#

Code like a Pro in C#

Jort Rodenburg

Publisher Resources

ISBN: 0596001819Catalog PageErrata