I'm working on application in C#, where I need to serialize and deserialize some classes into/from XML. This operations will be implemented in Class Library. I chose XMLSerialization class to serialize/deserialize these classes to XML file. As you know, this implementation uses reflection, which has the condition that the serialized/deserialized class needs to have a parameterless constructor. However, the serialized class has one parameter that is mandatory, which is good candidate as parameter for constructor, to be sure that it is properly initialized. I've created a manager class for serialization with two methods, one to store to file and one to load from file. I thought of multiple solutions:
- For serialized class create two constructors, one parameterless and other one with mandatory parameter. This class can be easily serialized, but can be badly initialized, which can cause problems (maybe in other places, for example if class is used in any web service).
- As this implementation is in class library, it is possible to create class A (to serialize), which will be public and will have one constructor with mandatory parameter. Managers methods will take as parameter this class A or return class A after is loaded. But internally I would create class B, which will be 1:1 as class A, but with parameterless constructor for serialization or deserialization purposes. This class B will be internal, which means, that it is visible only in current assembly, so it cannot happen, that it can be badly initialized when class library is linked. However, this causes duplicate code. Imagine, that there can be more classes like this and more complex. This means another expense.
- Last one solution, which comes to my mind is to implement serialization by myself using Linq to XML. This solution is safe and without duplicate code, but implementation is difficult for big classes. Or even worse, when we want to change element names or switch between elements and attributes, we have to go through this implementation every time carefully and change it (instead of changing attributes).
As I'm trying to find out a better solution (maybe there is another, which I don't know about) and get good manners in programming applications. What do you think, what is better solution (maybe in one scenario and in other scenario another solution)? To maintan duplicate code or complex code (maybe from real experience)?