title: How to serialize an UTF 8 xml string
body: <p>I had this code to create an xml. It used to work as expected, but in the first xml row, the encoding was set as utf-16.</p>
  
  <p>The code was:</p>
  
  <pre><code>public static string SerializeObject&lt;T&gt;(this T toSerialize)
  {
      XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
  
      using (StringWriter textWriter = new StringWriter())
      {
          xmlSerializer.Serialize(textWriter, toSerialize);
          return textWriter.ToString();
      }
  }
  </code></pre>
  
  <p>Since I need to encode it in UTF-8, I edit it as follows:</p>
  
  <pre><code>public static string SerializeObject&lt;T&gt;(this T toSerialize)
  {
      XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
  
  
      XmlWriterSettings settings = new XmlWriterSettings()
      {
          Encoding = new  UTF8Encoding(),
          Indent = false,
          OmitXmlDeclaration = false
      };
  
      using (StringWriter textWriter = new StringWriter())
      {
          using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
          {
              xmlSerializer.Serialize(xmlWriter, toSerialize);
          }
          return textWriter.ToString();
      }
  }
  </code></pre>
  
  <p>The code seems good, but the generated xml has still the row</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-16"?&gt;
  </code></pre>
  
  <p>and not</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  </code></pre>
  
  <p>Why? How can I create an utf-8 xml?</p>