To configure an application, I often create a configuration class with configuration values for the application, which I then deserialize into an object for use. The configuration object is usually bound to the user interface, so that the configuration can be modified and saved by the user. A configuration class usually has default values assigned to properties, so there is always a default configuration. It worked out well. I recently had a situation where I had a list of strings that provided some information about the default path. And what I saw made me realize that I didn’t quite understand how the properties of the object are populated during XML deserialization for the object.
So, I created a simple example to show the behavior. The following is a simple class that has several properties that have some default values for the code.
[Serializable]
public class TestConfiguration
{
public String Name
{
get
{
return mName;
}
set
{
mName = value;
}
}private String mName = "Pete Sebeck";
public List<String> Associates
{
get
{
return mAssociates;
}
set
{
mAssociates = value;
}
} private List<String> mAssociates = new List<string>() { "Jon", "Natalie" };
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.AppendLine(String.Format("Name: {0}", Name));
buffer.AppendLine("Associates:");
foreach(String associate in mAssociates)
{
buffer.AppendLine(String.Format("\t{0}", associate));
}
return buffer.ToString();
}
}
And the main thing is that it creates new objects, prints the state of the object on the console, serializes (xml) it to a file, restores the object from this file and displays the state of the object on the console again. What I expected was an object that matched what was serialized. I got a default object with the contents of a serialized list added by default.
static void Main(string[] args)
{
TestConfiguration configuration = new TestConfiguration();
Console.WriteLine(configuration.ToString());
XmlSerializer writer = new XmlSerializer(typeof(TestConfiguration));
StreamWriter filewriter = new StreamWriter("TestConfiguration.xml");
writer.Serialize(filewriter, configuration);
filewriter.Close();
XmlSerializer reader = new XmlSerializer(typeof(TestConfiguration));
StreamReader filereader = new StreamReader("TestConfiguration.xml");
TestConfiguration deserializedconfiguration = (TestConfiguration)reader.Deserialize(filereader);
filereader.Close();
Console.WriteLine(deserializedconfiguration.ToString());
Console.ReadLine();
}
Results:
Name: Pete Sebeck
Associates:
Jon
Natalie
Name: Pete Sebeck
Associates:
Jon
Natalie
Jon
Natalie
, , List , . - ? , , , . , , , . , , , , , .