title: Binary serialization in C# (really, WYSIWYG serialization)
body: <p>(for WYSIWYG I mean that <strong>I</strong> decide <strong>WHAT</strong> is written and <strong>HOW</strong> it's written, and not someone at Microsoft or at Google) (OK... Technically I don't decide anything... Someone that programmed some years ago decided, and I can only ask how much high I have to jump)</p>
  
  <p>I feel a little stupid today, but I've already lost two hours looking for the solution :-(. </p>
  
  <p>Now...</p>
  
  <p>I have a binary protocol. It's C based, so it's like looking at a C struct where the endianness of the machine is defined (and luckily it's the same as the "local" endianness), the size of the various types are defined, the data structure alignment is defined, the layout of the struct is defined, the strings are fixed arrays of chars in a know encoding... Everything is defined! And everything is very similar to a C# <code>unsafe struct</code> when you are using <code>[(LayoutKind.Explicit)]</code> and you are not very picky about using the <code>fixed</code> modifier for arrays. Now I need to serialize/deserialize it in C#... I've looked around but I wasn't able to find anything... What have I missed? Before you ask, I know of <code>BinaryFormatter</code>, but it isn't WYSIWYG enough for me... <code>BinaryFormatter</code> implements its formatting language. Yeah, I know of <code>BitConverter</code> (and of the fact that it doesn't implement the converters for big-endian), but it isn't a "complete" solution. It's only the "base" instrument. And I know of <code>BinaryWriter</code>/<code>BinaryReader</code>, but they don't seem to support arrays that aren't <code>byte[]</code> or <code>char[]</code> and they don't seem to be able to "pad" an array on write (you have a 5 elements <code>byte[]</code> array and you need to write it as a 10 elements <code>byte[]</code> array because the format you are using requires it... You have to write lines of code to do this)</p>
  
  <p>Plan B (but perhaps even Plan Z) is to create a shadow <code>unsafe struct</code> for each class, a <code>IWysiwygSerializable</code> interface with two methods (<code>Read</code> and <code>Write</code>) and implement the interface in every class (the write would populate the <code>unsafe struct</code> and write it in the output stream, the read would do the opposite) (or I could even do directly some tens of <code>BitConverter</code> in the <code>Read</code> and <code>Write</code> without using the <code>struct</code>, but for arrays it's a little more difficult)</p>
  
  <p>Thanks!</p>