0

I have created a type with System.Reflection.Emit following MSDN doc

I create my type and an instance with this code :

//following the tutorial I created a method which returns a dynamic type
Type myDynamicType = CreateNewObject("MyDynamicType", fields);
var instance = Activator.CreateInstance(myDynamicType);

now I want to seralize my object with XmlSerializer

tried this :

FileStream fs = new FileStream(@"C:\Test\SerializedDynamic.XML", FileMode.Create);            
XmlSerializer xs = new XmlSerializer(typeof(object));
xs.Serialize(fs, instance);

but it throws an exception :

"The type MyDynamicType was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."

Any help ?

svick
  • 236,525
  • 50
  • 385
  • 514
nemantro
  • 135
  • 1
  • 5
  • have you tried casting?, or this http://msdn.microsoft.com/en-gb/library/e5aakyae.aspx – Sayse Apr 05 '13 at 11:12
  • What happens if you do: `XmlSerializer xs = new XmlSerializer(myDynamicType);` ? – Jon Egerton Apr 05 '13 at 11:17
  • Can you do what it says you to do? Is it possible to add attributes to your dynamic type? Mainly `[XmlInclude]` which should tell what data type it is. However I think what problem is indeed what @JonEgerton found - you have to provide a type to serializer (could also try `new XmlSerializer(instance.GetType())` if you are passing instance as a parameter into method what performs serialization) – Sinatr Apr 05 '13 at 11:28
  • It worked. I don't know why I forgot to cast ! must get a coffee NOW ! thanks guys – nemantro Apr 05 '13 at 11:30

1 Answers1

3

Expanding on the comment:

I think the issue is that you're creating the XmlSerializer with typeof(object).

If you use either of the following it should work:

XmlSerializer xs = new XmlSerializer(myDynamicType);
XmlSerializer xs = new XmlSerializer(instance.GetType());
Jon Egerton
  • 40,401
  • 11
  • 97
  • 129