Partilhar via


Using XmlSerializer with internal classes

Normally, it is not possible to use XmlSerializer with internal classes.  However, it is possible to work around this issue, when the internal classes are written in C#.  

To do that, we need create a special build configuration, and '#if' block in the code to build a version of assembly, where those internal classes are public. (The result assembly is only used in the workaround, and could be discarded after that.)  Once we get this assembly, we can use sgen.exe in the framework to generate a serialization assembly for this assembly (with public classes.)  We need use command line option '/keep' when we do this. That option will leave the C# source code in the directory. However, the tool pick up a random name for this code file, so it is better to do this in an empty directory.  Once we get this C# code file, we will include it in the original project.  Because those generated classes have been built into the assembly, they can access internal classes correctly.  It is necessary to edit the generated code a little bit to remove assembly attribute, change the namespace of those classes to whatever we want, and maybe change the generated classes to internal as well.

We need change the code where XmlSerializer is created to use the generated Serializer. It is actually easier to use. With pre-generated code, it is also faster.  However, it is a problem to maintain the generated code up to date. We have to regenerate the code when the change in those classes impacts the serializer.  It is possible to do some scripting to make the whole process done automatically.