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

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:

   1: long? l = 84839; 


   3: System.IO.MemoryStream mem = new System.IO.MemoryStream(); 

   4: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = 

   5:     new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 


   7: formatter.Serialize(mem, l);


   9: byte[] bytes = mem.ToArray();


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.

Happy coding!


One Response to “Converting a Nullable Type to a Byte Array in C# .Net”

  1. frostwire download Says:

    one can argue that it can go both ways

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: