I want to save an object containing a value that can basically be any type. I am using XmlSerializer to do that and it works fine with one exception: If the value is an enum, the serializer stores the value as integer. If I load it back and use that value to read from a dictionary I get a KeyNotFoundException.
Is there any elegant way to save the enum as enum or to avoid the KeyNotFoundException and still use XmlSerializer? (Casting back to enum is not a good option here, the container and dictionary must support all types)
Here is a simplified piece of code that demonstrates the problem:
public enum SomeEnum
{
SomeValue,
AnotherValue
}
// Adding [XmlInclude(typeof(SomeEnum))] is no proper solution as Key can be any type
public class GenericContainer
{
public object Key { get; set; }
}
private Dictionary<object, object> SomeDictionary = new Dictionary<object, object>();
public void DoSomething()
{
SomeDictionary[SomeEnum.AnotherValue] = 123;
var value = SomeDictionary[SomeEnum.AnotherValue];
Save(new GenericContainer { Key = SomeEnum.AnotherValue}, "someFile.xml");
var genericContainer = (GenericContainer)Load("someFile.xml", typeof(GenericContainer));
// Throws KeyNotFoundException
value = SomeDictionary[genericContainer.Key];
}
public void Save(object data, string filePath)
{
var serializer = new XmlSerializer(data.GetType());
using (var stream = File.Create(filePath))
{
serializer.Serialize(stream, data);
}
}
public object Load(string filePath, Type type)
{
var serializer = new XmlSerializer(type);
using (var stream = File.OpenRead(filePath))
{
return serializer.Deserialize(stream);
}
}