You can write the fields one after another to the BinaryWriter:
User user = ...
using (BinaryWriter writer = ...)
{
writer.Write((byte)user.id);
writer.Write(user.age);
}
- BinaryWriter uses the endianness of the platform, i.e., little endian on x86/x64.
- "c – char – string of length 1 – 1 byte" is a byte in C#. Write(byte)
- "i – int – integer – 4 bytes" is an int in C#. Write(Int32)
There is no pack
/unpack
-like functionality built into the .NET Framework.1
1. When you're p/invoking native code, there's Interop Marshaling. But you're not p/invoking native code.