Quantcast
Channel: Serialize an object to string - Stack Overflow
Viewing all articles
Browse latest Browse all 12

Answer by Fulvio for Serialize an object to string

$
0
0

Code Safety Note

Regarding the accepted answer, it is important to use toSerialize.GetType() instead of typeof(T) in XmlSerializer constructor: if you use the first one the code covers all possible scenarios, while using the latter one fails sometimes.

Here is a link with some example code that motivate this statement, with XmlSerializer throwing an Exception when typeof(T) is used, because you pass an instance of a derived type to a method that calls SerializeObject<T>() that is defined in the derived type's base class: http://ideone.com/1Z5J1. Note that Ideone uses Mono to execute code: the actual Exception you would get using the Microsoft .NET runtime has a different Message than the one shown on Ideone, but it fails just the same.

For the sake of completeness I post the full code sample here for future reference, just in case Ideone (where I posted the code) becomes unavailable in the future:

using System;using System.Xml.Serialization;using System.IO;public class Test{    public static void Main()    {        Sub subInstance = new Sub();        Console.WriteLine(subInstance.TestMethod());    }    public class Super    {        public string TestMethod() {            return this.SerializeObject();        }    }    public class Sub : Super    {    }}public static class TestExt {    public static string SerializeObject<T>(this T toSerialize)    {        Console.WriteLine(typeof(T).Name);             // PRINTS: "Super", the base/superclass -- Expected output is "Sub" instead        Console.WriteLine(toSerialize.GetType().Name); // PRINTS: "Sub", the derived/subclass        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));        StringWriter textWriter = new StringWriter();        // And now...this will throw and Exception!        // Changing new XmlSerializer(typeof(T)) to new XmlSerializer(subInstance.GetType());         // solves the problem        xmlSerializer.Serialize(textWriter, toSerialize);        return textWriter.ToString();    }}

Viewing all articles
Browse latest Browse all 12

Trending Articles