Question

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 ?

Was it helpful?

Solution

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());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top