Page 154 - CSharp/C#
P. 154

Chapter 19: Binary Serialization




        Remarks



        The binary serialization engine is part of the .NET framework, but the examples given here are
        specific to C#. As compared to other serialization engines built into the .NET framework, the binary
        serializer is fast and efficient and usually requires very little extra code to get it to work. However, it
        is also less tolerant to code changes; that is, if you serialize an object and then make a slight
        change to the object's definition, it likely will not deserialize correctly.


        Examples



        Making an object serializable


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


         [Serializable]
         public class Vector
         {
             public int X;
             public int Y;
             public int Z;

             [NonSerialized]
             public decimal DontSerializeThis;

             [OptionalField]
             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.


        Controlling serialization behavior with attributes


        If you use the [NonSerialized] attribute, then that member will always have its default value after
        deserialization (ex. 0 for an int, null for string, false for a bool, etc.), regardless of any initialization
        done in the object itself (constructors, declarations, etc.). To compensate, the attributes
        [OnDeserializing] (called just BEFORE deserializing) and [OnDeserialized] (called just AFTER
        deserializing) together with their counterparts, [OnSerializing] and [OnSerialized] are provided.




        https://riptutorial.com/                                                                             100
   149   150   151   152   153   154   155   156   157   158   159