You should consider serialization when designing new classes, because a class cannot be made serializable after it has been compiled. Some questions to ask are: Will this class need to be sent across application domains? Will this class ever be used with remoting? What will users do with this class — might they derive a new class from mine that needs to be serialized? When in doubt, mark the class as serializable. It is probably better to mark all classes as serializable unless any of the following are true:
- The class will never cross an application domain. If serialization is not required and the class needs to cross an application domain, derive the class from MarshalByRefObject.
- The class stores special pointers that are only applicable to the current instance of the class. If a class contains unmanaged memory or file handles, for example, ensure these files are marked as NonSerialized, or don't serialize the class at all.
- Class data members contain sensitive information. In this case, it is advisable to mark the class as serializable, but to mark the individual data members that contain sensitive information as NonSerialized. Another alternative is to implement the ISerializable interface and serialize only the required fields.
Be aware of the security implications of marking a class as serializable. A Link Demand or an Inheritance Demand for a CodeAccessPermission on a class or class constructor can be bypassed by default or custom serialization that implements a corresponding demand for the same CodeAccessPermission. If a class has a Link Demand for a permission, the runtime checks only the immediate caller to verify that the caller has been granted the permission. The .NET Framework class library code is signed with the Microsoft strong name and is always granted full trust. Any code can use code that is granted full trust to bypass link-time security checks. For example, in the case of serialization, malicious code that does not have the required serialization permission can call one of the fully trusted .NET Framework formatters, such as BinaryFormatter, and bypass the link-demand check for the permission.