This past week I found myself in need of retrieving a byte array (byte) representation of a nullable long (long?) in C#. I was trying to serialize an anchor being passed around by MS Sync Framework and we’d chosen long ago to use long?’s to accomplish our anchoring.
When converting any primitive type to a byte array, you can easily make use of the System.BitConverter class. It’s pretty great, really. But for non-primitives, which includes nullable versions of primitives, you must get a little more technical in your approach.
The following code worked for me:
Basically, you create a memory stream and a binary formatter, then pass your object to the stream and ask the formatter to serialize it. Calling the ToArray() method at the end will return you a nice, crisp byte array of your object, which you can pretty much do anything with.