title: Using StringWriter for XML Serialization
body: <p>I'm currently searching for an easy way to serialize objects (in C# 3).</p>
  
  <p>I googled some examples and came up with something like:</p>
  
  <pre><code>MemoryStream memoryStream = new MemoryStream ( );
  XmlSerializer xs = new XmlSerializer ( typeof ( MyObject) );
  XmlTextWriter xmlTextWriter = new XmlTextWriter ( memoryStream, Encoding.UTF8 );
  xs.Serialize ( xmlTextWriter, myObject);
  string result = Encoding.UTF8.GetString(memoryStream .ToArray());
  </code></pre>
  
  <p>After reading this <a href="https://stackoverflow.com/questions/1138414/can-i-serialize-xml-straight-to-a-string-instead-of-a-stream-with-c">question</a> I asked myself, why not using StringWriter? It seems much easier.</p>
  
  <pre><code>XmlSerializer ser = new XmlSerializer(typeof(MyObject));
  StringWriter writer = new StringWriter();
  ser.Serialize(writer, myObject);
  serializedValue = writer.ToString();
  </code></pre>
  
  <p>Another Problem was, that the first example generated XML I could not just write into an XML column of SQL Server 2005 DB.</p>
  
  <p>The first question is: Is there a reason why I shouldn't use StringWriter to serialize an Object when I need it as a string afterwards? I never found a result using StringWriter when googling.</p>
  
  <p>The second is, of course: If you should not do it with StringWriter (for whatever reasons), which would be a good and correct way?</p>
  
  <hr>
  
  <p>Addition:</p>
  
  <p>As it was already mentioned by both answers, I'll further go into the XML to DB problem.</p>
  
  <p>When writing to the Database I got the following exception:</p>
  
  <blockquote>
    <p>System.Data.SqlClient.SqlException:
    XML parsing: line 1, character 38,
    unable to switch the encoding</p>
  </blockquote>
  
  <p>For string</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;test/&gt;
  </code></pre>
  
  <p>I took the string created from the XmlTextWriter and just put  as xml there. This one did not work (neither with manual insertion into the DB).</p>
  
  <p>Afterwards I tried manual insertion (just writing INSERT INTO ... ) with encoding="utf-16" which also failed.
  Removing the encoding totally worked then. After that result I switched back to the StringWriter code and voila - it worked.</p>
  
  <p>Problem: I don't really understand why.</p>
  
  <p>at Christian Hayter: With those tests I'm not sure that I have to use utf-16 to write to the DB. Wouldn't setting the encoding to UTF-16 (in the xml tag) work then?</p>