I'm using XML serialization to produce a file in a format specific to another application. One of the requirements is that all booleans be represented as 1 or 0. I've looked at some possibilities, including a struct to handle this easily and seamlessly. Currently I'm looking into another venue, which is to use an enum.
public enum BoolEnum
{
[XmlEnum("0")]
False = 0,
[XmlEnum("1")]
True = 1
}
So far, it works wonderfully, and it's much cleaner. BUT (!) I'm also trying to make the deserialization easy, and I'd just like to be able to handle errors. If I produce an invalid tag:
<invalid>2</invalid>
to be deserialized as BoolEnum, I get an InvalidOperationException inside another InvalidOperationException. How can I catch that exception in an enum?
Addendum:
Deserialization function:
static void Deserialize<T>(out T result, string sourcePath) where T : class
{
FileStream fileStream = null;
try
{
fileStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
result = xmlSerializer.Deserialize(fileStream) as T;
}
finally
{
if (fileStream != null)
fileStream.Close();
}
}
Deserialized object:
public class Test
{
[XmlElement("someboolvalue")
public BoolEnum SomeBoolValue { get; set; }
}