Making an object serializable
suggest changeAdd the [Serializable] attribute to mark a type so its fields can be binary-serialized:
[Serializable]
public class Vector
{
public int X;
public int Y;
public int Z;
[NonSerialized]
public decimal DontSerializeThis;
[OptionalField]
public string Name;
}
All fields will be serialized unless we explicitly opt out using the [NonSerialized] attribute. In our example, X, Y, Z, and Name are all serialized.
All fields 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents