DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Convert Object To Byte Array And Viceversa (serialization)

  • submit to reddit

// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
    if(obj == null)
        return null;
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);
    return ms.ToArray();
// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
    MemoryStream memStream = new MemoryStream();
    BinaryFormatter binForm = new BinaryFormatter();
    memStream.Write(arrBytes, 0, arrBytes.Length);
    memStream.Seek(0, SeekOrigin.Begin);
    Object obj = (Object) binForm.Deserialize(memStream);
    return obj;
p.s. for custom classes add [Serializable] attribute to enable serialization 


Snippets Manager replied on Mon, 2010/07/12 - 10:37am

thanks mate.. great great post..

Snippets Manager replied on Mon, 2011/07/11 - 11:45am

While this works it seems to copy all the data in the object twice, leading to poor performance. A performance trace with visual studio for a large object shows 1.7 sec spent on .Serialize() and 1.2 sec spent on .ToArray() Is there a way to copy the data of the object only once?

Snippets Manager replied on Wed, 2011/05/11 - 10:44am

Thanks for this code.I wanna serialize an object in order to send it via RTP packet. The problem is when i try to send an object intance (instances of classes i made)after its serialization.It seems like it is not arrived to its destination.But with predefined objects(int , double..), it work very well.the serialization without sending just work fineon both but this problem is just when i send the bytes serialized of an class's instanciation.

Snippets Manager replied on Fri, 2011/01/28 - 3:35pm

Thanks - Nice little utility. I already added it to my toolbox! One the I ran into was serializing a an object that had a PropertyChangedEventHandler. I found out here ( that the field needs to be prefixed with [field: NonSerialized]. That seemed to fix my problems.

Snippets Manager replied on Tue, 2010/11/02 - 4:39am

great code, thanks

Snippets Manager replied on Fri, 2009/12/04 - 12:15pm

Thanks dude that's exactly was I was looking for to serialize my class for remoting. Cheers. Computer Desks.