title: Easier way to serialize C# class as XML text
body: <p>While trying to answer another question, I was serializing a C# object to an XML string.  It was surprisingly hard; this was the shortest code snippet I could come up with:</p>
  
  <pre><code>var yourList = new List&lt;int&gt;() { 1, 2, 3 };
  var ms = new MemoryStream();
  var xtw = new XmlTextWriter(ms, Encoding.UTF8);
  var xs = new XmlSerializer(yourList.GetType());
  xs.Serialize(xtw, yourList);
  var encoding = new UTF8Encoding();
  string xmlEncodedList = encoding.GetString(ms.GetBuffer());
  </code></pre>
  
  <p>The result is okay:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;ArrayOfInt
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
      &lt;int&gt;1&lt;/int&gt;
      &lt;int&gt;2&lt;/int&gt;
      &lt;int&gt;3&lt;/int&gt;
  &lt;/ArrayOfInt&gt;
  </code></pre>
  
  <p>But the snippet is more complicated than I think it should be.  I can't believe you have to know about encoding and MemoryStream for this simple task.</p>
  
  <p>Is there a shorter way to serialize an object to an XML string?</p>