When you’re writing an API that deals with a TCP client, you need to talk data in terms of byte arrays.
BitConverter
BitConverter is a class in the System namespace that lets you convert numerical data types (and single chars) to and from their byte[] counterparts.
In order to convert to a byte[], just call GetBytes
To convert from a byte[] to an object, call the appropriate function for the data type you’re expecting:
Building a Better byte[] Producer
Since GetBytes is overloaded to accept any primitive you give it, we can easily make a little helper class to generate a long byte[] from any number of parameters presented to it.
To do this, we can accept any number of parameters using the params keyword in the function. This lets us pass in an indeterminate amount of variables to the function, which we can access as an array in the function body. Since everything inherits object, we can genericize the parameter to object[]. Then the only challenging thing is to cast each object as its appropriate primitive in order to give BitConverter the right overload.
Since you need to know the format of an incoming byte[] in order to parse it out into its primitive components, there isn’t an easy, one method solution. However, if you build up the right framework for defining the protocol, you can ease the pain quite a bit. I’ll probably end up making a post about it soon, but, for now…