I'm working with an XML structure that requires booleans to be represented as 1 or 0.
So, suppose the XML output has to look like:
<valid>1</valid>
Several nodes can be represented this way, so I made a struct to handle this. The solution I found works, but lacks oomph. OK, no, it doesn't just lack oomph, it sucks.
(Implemented in .NET 4)
public struct MyCrappyBool : IXmlSerializable
{
private int _IntValue;
private bool _BoolValue;
public int IntValue
{
get { return _IntValue; }
set
{
if (value < 0 || value > 1)
throw new ArgumentOutOfRangeException();
_IntValue = value;
_BoolValue = value == 1;
}
}
public bool BoolValue
{
get { return _BoolValue; }
set
{
_BoolValue = value;
_IntValue = value ? 1 : 0;
}
}
public MyCrappyBool(int intValue) : this()
{
IntValue = intValue;
}
public MyCrappyBool(bool boolValue): this()
{
BoolValue = boolValue;
}
#region IXmlSerializable Members
public XmlSchema GetSchema() { return null; }
public void ReadXml(XmlReader reader)
{
IntValue = int.Parse(reader.ReadString());
}
public void WriteXml(XmlWriter writer)
{
writer.WriteString(IntValue.ToString());
}
#endregion
}
This is incredibly tedious, first and foremost because I need to instantiate every time:
MyCrappyBool isValid = new MyCrappyBool(true);
But even then, some nifty implicit overloading can address that:
public static implicit operator MyCrappyBool(bool boolValue)
{
return new MyCrappyBool(boolValue);
}
public static implicit operator MyCrappyBool(int intValue)
{
return new MyCrappyBool(intValue);
}
That's still a lot of code for one... crappy boolean.
Later, it can be (XML) serialized as part of any other class:
[XmlElement("valid")]
public MyCrappyBool IsValid { get; set; }
[XmlElement("active")]
public MyCrappyBool IsActive { get; set; }
Is there a simpler way about this I'm not seeing?
Update: Reverse implicit operator overloading!
public static implicit operator bool(MyCrappyBool myCrappyBool)
{
return myCrappyBool.BoolValue;
}
public static implicit operator int(MyCrappyBool myCrappyBool)
{
return myCrappyBool.IntValue;
}
This means all my properties can be private.