Search code examples
c#serializationbinarywriter

C# and .NET: How to serialize a structure into a byte[] array, using BinaryWriter?


How to serialize a rather complex structure into a byte[] array, using BinaryWriter?

Update:

  • For this to work, every structure (and sub-structure?) must be decorated with the [Serializable] attribute.

  • I do not need to implement the ISerializable interface, as this is designed to give an object control over its own serialization.


Solution

  • From comments, the OP's scenario requires strong compatibility with future versions of the application / .NET, in which case I always advise againt BinaryFormatter - it has many "features" that simply don't work well between versions (and certainly not between platforms).

    I recommend looking at contract-based serializers; I'm biased, but I lean towards protobuf-net (which maps to Google's protobuf specification). The easiest way to do this is to attribute the types in such a way that the library can make light work of them (although it can also be done without attributes), for example:

     [ProtoContract]
     public class Customer {
         [ProtoMember(1)]
         public List<Order> Orders {get {....}}
    
         [ProtoMember(2)]
         public string Name {get;set;}
    
         ... etc
     }
    

    (the attribute appoach is very familiar if you've done any XmlSerializer or DataContractSerializer work - and indeed protobuf-net can consume the attributes from those if you don't want to add protobuf-net specific attributes)

    then something like:

    Customer cust = ...
    byte[] data;
    using(var ms = new MemoryStream()) {
        Serializer.Serialize(ms, cust);
        data = ms.ToArray();
    }
    

    The data produced this way is platform independent, and could be loaded on any matching contract (it doesn't even need to be Customer - it could any type with matching layout via the attributes). Indeed, in most cases it'll load easily into any other protobuf implementation - Java, C++, etc.