fork(12) download
  1. using System;
  2. using System.Xml.Serialization;
  3. using System.IO;
  4.  
  5. public class Test
  6. {
  7. public static void Main()
  8. {
  9. Sub subInstance = new Sub();
  10. Console.WriteLine(subInstance.TestMethod());
  11. }
  12.  
  13. public class Super
  14. {
  15. public string TestMethod() {
  16. return this.SerializeObject();
  17. }
  18. }
  19.  
  20. public class Sub : Super
  21. {
  22. }
  23. }
  24.  
  25. public static class TestExt {
  26. public static string SerializeObject<T>(this T toSerialize)
  27. {
  28. Console.WriteLine(typeof(T).Name); // PRINTS: "Super", the base/superclass -- Expected output is "Sub" instead
  29. Console.WriteLine(toSerialize.GetType().Name); // PRINTS: "Sub", the derived/subclass
  30.  
  31. XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
  32. StringWriter textWriter = new StringWriter();
  33.  
  34. // And now...this will throw and Exception!
  35. // Changing new XmlSerializer(typeof(T)) to new XmlSerializer(subInstance.GetType());
  36. // solves the problem
  37. xmlSerializer.Serialize(textWriter, toSerialize);
  38. return textWriter.ToString();
  39. }
  40. }
Runtime error #stdin #stdout 0.08s 43192KB
stdin
Standard input is empty
stdout
Super
Sub