Selective serialization

A class often contains fields that shouldn't be serialized. For example, assume a class stores a thread ID in a member variable. When the class is deserialized, the thread stored the ID for when the class was serialized might no longer be running; so serializing this value doesn't make sense. You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows.

public class MyObject   
  public int n1;  
  [NonSerialized] public int n2;  
  public String str;  

If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data. If you don't exclude these fields from serialization, be aware that the data they store are exposed to any code that has permission to serialize. For more information about writing secure serialization code, see Security and Serialization.


Binary serialization can be dangerous. Never deserialize data from an untrusted source and never round-trip serialized data to systems not under your control.

See also

Binary Serialization
XML and SOAP Serialization
Security and Serialization