Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Use a <a href="http://msdn.microsoft.com/en-us/library/system.io.stringwriter.aspx" rel="noreferrer"><code>StringWriter</code></a> instead of a <a href="http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx" rel="noreferrer"><code>StreamWriter</code></a>:</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>Note, it is important to use <code>toSerialize.GetType()</code> instead of <code>typeof(T)</code> in XmlSerializer constructor: if you use the first one the code covers all possible subclasses of <code>T</code> (which are valid for the method), while using the latter one will fail when passing a type derived from <code>T</code>.    Here is a link with some example code that motivate this statement, with <code>XmlSerializer</code> throwing an <code>Exception</code> when <code>typeof(T)</code> is used, because you pass an instance of a derived type to a method that calls SerializeObject that is defined in the derived type's base class: <a href="http://ideone.com/1Z5J1" rel="noreferrer">http://ideone.com/1Z5J1</a>.</p> <p>Also, Ideone uses Mono to execute code; the actual <code>Exception</code> you would get using the Microsoft .NET runtime has a different <code>Message</code> than the one shown on Ideone, but it fails just the same.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload