packing fields of a class into a byte array in c#

Posted by alex on Stack Overflow See other posts from Stack Overflow or by alex
Published on 2010-05-25T17:42:49Z Indexed on 2010/05/25 18:01 UTC
Read the original article Hit count: 244

Filed under:

Hi all:

I am trying to create a fast way to convert c# classes into byte array. I thought of serializing the class directly to a byte array using an example I found:

// 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();
}

But the byte array I got contains some other information that are not related to the fields in the class. I guess it is also converting the Properties of the class.

Is there a way to serialize only the fields of the class to a byte array?

Thanks

© Stack Overflow or respective owner

Related posts about c#