Search code examples
c#.netserializationidisposablememorystream

Object Serialization and IDisposable


        public static  string SerializeObject<T>(T obj)
        {
           try
           {
              string xmlString = null;
              MemoryStream memoryStream = new MemoryStream();
              XmlSerializer xs = new XmlSerializer(typeof(T));
              XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
              xs.Serialize(xmlTextWriter, obj);
              memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
              xmlString = UTF8ByteArrayToString(memoryStream.ToArray());      return xmlString;
           }
           catch
           {
              return string.Empty;
           }
        }

this is from - Link

Is there a way to write this where the memoryStream object doesn't need to be reassigned? Shouldn't it be disposed (wrapped in a using block)? What is the memoryStream used then reassigned?


Solution

  • You are correct. You should wrapped the stream in a using block. And the reassignment is not allowed when the variable is used in the using block. And its not even needed to do the serializing. You could do it like this:

    public static string SerializeObject<T>(T obj)
    {
        try
        {
             string xmlString = null;
             using (MemoryStream memoryStream = new MemoryStream())
             {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                xs.Serialize(xmlTextWriter, obj);
                xmlString = UTF8ByteArrayToString(memoryStream.ToArray()); 
                return xmlString;
            }
         }
         catch
         {
             return string.Empty;
         }
    }