Pages

Categories

Converting a Nullable Type to a Byte Array in C# .Net

November 5, 2010 — liberatedsoftware

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.

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.