C# Language Making an object serializable


Add the [Serializable] attribute to mark an entire object for binary serialization:

public class Vector
    public int X;
    public int Y;
    public int Z;

    public decimal DontSerializeThis;

    public string Name;

All members will be serialized unless we explicitly opt-out using the [NonSerialized] attribute. In our example, X, Y, Z, and Name are all serialized.

All members are required to be present on deserialization unless marked with [NonSerialized] or [OptionalField]. In our example, X, Y, and Z are all required and deserialization will fail if they are not present in the stream. DontSerializeThis will always be set to default(decimal) (which is 0). If Name is present in the stream, then it will be set to that value, otherwise it will be set to default(string) (which is null). The purpose of [OptionalField] is to provide a bit of version tolerance.