Serialization Sample
This solution demonstrates how to serialize and deserialize an object.
To get samples and instructions for installing them
Do one or more of the following:
On the Help menu, click Samples.
The Readme displays information about samples.
Visit the Visual Studio 2008 Samples Web site. The most recent versions of samples are available there.
Locate samples on the computer on which Visual Studio is installed. By default, samples and a Readme file are installed in drive:\Program Files\Microsoft Visual Studio 9.0\Samples\lcid. For Express editions of Visual Studio, all samples are located online.
For more information, see Visual Studio Samples.
Security Note: |
---|
This sample code is intended to illustrate a concept, and it shows only the code that is relevant to that concept. It may not meet the security requirements for a specific environment, and it should not be used exactly as shown. We recommend that you add security and error-handling code to make your projects more secure and robust. Microsoft provides this sample code "AS IS" with no warranties. |
To run this sample
- Press F5.
Demonstrates
This application contains two classes, one with standard serialization and one with custom serialization. The user interface includes buttons to serialize and deserialize the two classes. The class with standard serialization can be serialized to either a SOAP file or a binary file. The class with custom serialization is serialized to a SOAP file. A TextBox control is used to display the SOAP files. The two classes both have the SerializableAttribute attribute. The classes are described in the following table.
Class Member |
SerializationClass |
CustomSerializationClass |
---|---|---|
PublicVariable |
The public variable is serialized and deserialized without change. |
The public variable is serialized and deserialized without change. |
PublicProperty |
The private variable that supports the property is serialized and deserialized without change. |
The private variable that supports the property is serialized as -1, regardless of the value set in the user interface. It is therefore deserialized as -1. |
NonSerializedVariable |
This variable is not serialized, because it is marked with the NonSerializedAttribute. The public variable is not serialized, and the deserialized value is 0. |
Though the variable is marked by the NonSerializedAttribute, it is serialized, because the custom serialization overrides this setting. The public variable is serialized and deserialized without change. |
Three types of serialization are demonstrated:
SOAP formatting Class1 is serialized using the SoapFormatter class.
Binary formatting Class1 is serialized using BinaryFormatter class.
Custom formatting Class2 implements the ISerializable interface, including the GetObjectData method to perform custom serialization.