Debugging into the .NET XmlSerializer

I've had several occasions now where someone with Sogeti or someone at a client has had a "truly mysterious" problem where the XmlSerializer was throwing an error which the programmer simply couldn't understand.  When situations like this arise, I find myself reaching for a great post written by Scott Hanselman on this issue which I will repeat the meat of which here so that I've got a copy of my own.

If you find yourself needing to debug the code generated by the XmlSerializer to serialize or deserialize your type, here is what you need to do:

1. Modify your app.config or web.config to include the following:

 1: <?xml version="1.0" encoding="utf-8" ?>
 2: <configuration>
 4: <switches>
 5:<add name="XmlSerialization.Compilation" value="1" />
 6: </switches>
 8: </configuration>

2. Recompile your application and set a break point just after you create your XmlSerializer.

3. Open the directory "C:\Documents and Settings\[username]\Local Settings\Temp"

4. Find the .CS file with the most recent timestamp, it will have a random file name.

5. Open that file in the same Visual Studio you've got debugging, and set a break point.

6. Debug to your hearts content.

Important to remember at this point is that this code is generated by the system and is meant to be fast, not friendly.  You'll need to be very familiar with the XmlReader object or you won't understand how it is doing what it is doing.  Also realize that you can't control that code, you can only control the attributes on the Type you gave it, and from that it will generate the code as it sees fit.

Side Note : One of the classic performance mistakes I see people make when they start doing a lot of XML serialization is to create the XmlSerializer object every time they need one.  The constructor of the XmlSerializer is the most expensive part of it's operations.  It is there that the code is generated which you are debugging above, and so once you've created an XmlSerializer if you've got a reasonable expectation of needing it again then keep it around!