I’ve recently been exposed to some code which consistently uses Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializerContract.getSerializer(typeof(X)) to create a new serializer, where X is the type of object being deserialized. When looking up documentation, most documentation would use new XmlSerializer(typeof(X)), and I could hardly find any documentation on XmlSerializerContract (and the only official documentation I did find pertained to Outlook).
What are the benefits to using Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializerContract.getSerializer() versus new XmlSerializer()? Under what scenarios would I want to use each?
For performance optimization,
XmlSerializer(andXmlSerializerFactory) generate temporary assembly containing serializer for particular types. The type that you have mentioned (Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializerContract) are from these generated assemblies (see http://treyhutcheson.wordpress.com/2007/02/20/dynamic-interface-implementations/) – so it’s quite natural that you haven’t found any documentation for the same.Frankly, to me it seems to be some hack solution probably to work-around memory leak issues related XmlSerializer – unless specific constructors are used, XmlSerializer would keep on generating more dynamic assemblies and thereby increasing memory foot-print. Quote from MSDN on the same:
My advise would be to of course find out the actual reason for using undocumented code from generated assembly from concerned developers but regardless prepare to migrate away from the same by using
XmlSerializer/XmlSerializerFactory– you can always use your own caching solution if needed (in case you are not using those two particular constructors). Don’t forget to test your code rigorously.