Serializing a class to a byte[]

I’m trying to serialize a class that I made to a byte array so that I can easily pass it over a network stream.
I am having an issue with the following exception when trying to serialize my object “System.NotImplementedException”.
It doesn’t provide anymore information about the exception.


[Serializable]
public class Payload
{
    private const int maxByteArrayLength = 4;
    private byte[] address = new byte[maxByteArrayLength];
    private DeviceType deviceType;
    private RequestFlag requestFlag;
    private int messageValue;
    private DateTime time;
    ...
}
...
private void SerializeMyObject(ref Payload ms, out byte[] data)
{
   data = Reflection.Serialize(ms, typeof(Payload));
}
private void DeserializeMyObject(out Payload ms, ref byte[] data)
{
    ms = (Payload)Reflection.Deserialize(data, typeof(Payload));
}

I would much appreciate any advice on how to serialize my object correctly.

EDIT: DeviceType & RequestFlag are both public enums.

Do a search from the top of the page for “serialization”. You will find lots of discussions.

You cannot directly serialize classes. You have to serialize the properties by hand.

This BitConverter can ba handy:

https://bitbucket.org/aalmada/hydramf/src/779d1c524a9c/HydraMF.Hardware/BitConverter.cs

@ JPenny1993 - Use:

payload = Reflection.Deserialize(ioBuffer, null) as Payload;

byte[] ioBuffer = Reflection.Serialize(Payload, null);

@ Robvan:

Your right. Interesting. I didn’t realize that serialization is available on the bigger GHI devices. I always stuck to BitConverters and thought that’s the only way.

Thanks RobvanSchelven;

The code you supplied works brilliantly on my Spider. I can’t say the same for the Netduino Plus which I am also using, but I now understand why. Sorry I didn’t specify the hardware I was using.

Thanks Peter B;

The BitConverter you linked me to looks like it is what will fix my issue.

@ JPenny1993 - FYI, I just posted some code that I use to serialize a class to a byte[]. See here: https://www.ghielectronics.com/community/forum/topic?id=14938