I really like the extension method that TWith2Sugars posted here. I ran into an odd problem though. When I put this into a shared class library and call the serialization function, I get the following error:
The type MyType was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
I looked around a bit and found that the XmlSerializer can only serialize types that it is aware of. I interpret this to mean classes that are in the class library, not the project that I build based off that libary.
Is there a way around this? Can this function be placed into a class library or does it need to be in each project that uses it?
Update:
I figured out what was causing the problem. I had the following code:
object o = new MyClass();
o.Serialize();
This was causing the error. When I changed the code to:
MyClass c = new MyClass();
c.Serialize();
Everything ran fine. So, lesson learned - don't try to (de)serialize generic objects. The thing I liked the most about the link I referenced was that I did not have to put any XML attribute tags on my classes. The extension method just worked.
For purposes of closing out the question, I will award the answer to whoever expands on Marc's answer (including Marc) with a code sample illustrating the use of [XmlInclude].