How to convert byte array to any type

Primitive types are easy because they have a defined representation as a byte array. Other objects are not because they may contain things that cannot be persisted, like file handles, references to other objects, etc.

You can try persisting an object to a byte array using BinaryFormatter:

public byte[] ToByteArray<T>(T obj)
{
    if(obj == null)
        return null;
    BinaryFormatter bf = new BinaryFormatter();
    using(MemoryStream ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

public T FromByteArray<T>(byte[] data)
{
    if(data == null)
         return default(T);
    BinaryFormatter bf = new BinaryFormatter();
    using(MemoryStream ms = new MemoryStream(data))
    {
        object obj = bf.Deserialize(ms);
        return (T)obj;
    }
}

But not all types are serializable. There’s no way to “store” a connection to a database, for example. You can store the information that’s used to create the connection (like the connection string) but you can’t store the actual connection object.


UPDATE

BinaryFormatter is now considered “insecure“, especially when trying to deserialize data from untrusted sources. Which makes sense, since you’re essentially loading raw binary data into memory that could do bad things.

Suggested alternatives are to use a non-binary format like XML or JSON for generic object graphs, or write custom binary serialization code to serialize primitive members explicitly.

Leave a Comment