Steve H. Steve H. - 4 months ago 29
C# Question

Convert any object to a byte[]

I am writing a prototype TCP connection and I am having some trouble homogenizing the data to be sent.

At the moment, I am sending nothing but strings, but in the future we want to be able to send any object.

The code is quite simple at the moment, because I thought everything could be cast into a byte array:

void SendData(object headerObject, object bodyObject)
byte[] header = (byte[])headerObject; //strings at runtime,
byte[] body = (byte[])bodyObject; //invalid cast exception

// Unable to cast object of type 'System.String' to type 'System.Byte[]'.

This of course is easily enough solved with a

if( state.headerObject is System.String ){...}

The problem is, if I do it that way, I need to check for EVERY type of object that can't be cast to a byte[] at runtime.

Since I do not know every object that can't be cast into a byte[] at runtime, this really isn't an option.

How does one convert any object at all into a byte array in C# .NET 4.0?


Use the BinaryFormatter:

byte[] ObjectToByteArray(object obj)
    if(obj == null)
        return null;
    BinaryFormatter bf = new BinaryFormatter();
    using (MemoryStream ms = new MemoryStream())
        bf.Serialize(ms, obj);
        return ms.ToArray();

Note that obj and any properties/fields within obj (and so-on for all of their properties/fields) will all need to be tagged with the Serializable attribute to successfully be serialized with this.