You may need to add serialization support to a class if you need to be able to marshal it by value across a .NET remoting boundary (that is, across application domains, processes, or computers) or if you want to be able to persist the object state to create a flat data stream, perhaps for storage on the file system.
By default, classes cannot be serialized. A class can be serialized if it is marked with the SerializableAttribute or if it derives from ISerializable . If you use serialization:
Do not serialize sensitive data .
Validate serialized data streams .
Ideally, if your class contains sensitive data, do not support serialization. If you must be able to serialize your class and it contains sensitive data, avoid serializing the fields that contain the sensitive data. To do this, either implement ISerializable to control the serialization behavior or decorate fields that contain sensitive data with the [ NonSerialized ] attribute. By default, all private and public fields are serialized.
The following example shows how to use the [ NonSerialized ] attribute to ensure a specific field that contains sensitive data cannot be serialized.
[Serializable] public class Employee { // OK for name to be serialized private string name; // Prevent salary being serialized [NonSerialized] private double annualSalary; . . . }
Alternatively, implement the ISerializable interface and explicitly control the serialization process. If you must serialize the sensitive item or items of data, consider encrypting the data first. The code that de-serializes your object must have access to the decryption key.
When you create an object instance from a serialized data stream, do not assume the stream contains valid data. To avoid potentially damaging data being injected into the object, validate each field as it is reconstituted as shown in the following code sample.
public void DeserializationMethod(SerializationInfo info, StreamingContext cntx) { string someData = info.GetString("someName"); // Use input validation techniques to validate this data. }
For more information about input validation techniques, see "Input Validation" in Chapter 10, "Building Secure ASP.NET Pages and Controls."
If your code supports partial trust callers , you need to address additional threats. For example, malicious code might pass a serialized data stream or it might attempt to serialize the data on your object. For risk mitigation techniques to address these threats, see "Serialization" in Chapter 8, "Code Access Security in Practice."