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

Alessandro has posted 1 posts at DZone. You can read more from them at their website. View Full User Profile

Get any object size in kb

10.12.2012
| 4426 views |
  • submit to reddit
public static int GetObjSize(Object obj)
        {
            try
            {
                string XmlString = string.Empty;
                MemoryStream MemStream = new MemoryStream();
                XmlSerializer Serializer = new XmlSerializer(obj.GetType());
                XmlTextWriter XmlText = new XmlTextWriter(MemStream, Encoding.Default);
                Serializer.Serialize(XmlText, obj);
                byte[] bytes = new byte[] { };
                bytes = MemStream.ToArray();
                XmlString = Encoding.Default.GetString(bytes, 0, bytes.Length);
                MemStream.Flush();
                MemStream.Close();
                XmlText.Flush();
                XmlText.Close();

                byte[] bytesobj = new byte[XmlString.Length * sizeof(char)];
                Buffer.BlockCopy(XmlString.ToCharArray(), 0, bytes, 0, bytes.Length);
                return bytesobj.Length;
            }
            catch (Exception e)
            {
                return -1;
            }
        }