Serialize a nullable int
I'm using this micro-pattern to implement Nullable serialization:
[XmlIgnore]
public double? SomeValue { get; set; }
[XmlAttribute("SomeValue")] // or [XmlElement("SomeValue")]
[EditorBrowsable(EditorBrowsableState.Never)]
public double XmlSomeValue { get { return SomeValue.Value; } set { SomeValue= value; } }
[EditorBrowsable(EditorBrowsableState.Never)]
public bool XmlSomeValueSpecified { get { return SomeValue.HasValue; } }
This provides the right interface to the user without compromise and still does the right thing when serializing.
I figured out a workaround utilizing two properties. An int? property with an XmlIgnore attribute and an object property which gets serialized.
/// <summary>
/// Score db record
/// </summary>
[System.Xml.Serialization.XmlIgnore()]
public int? ID
{
get
{
return iID_m;
}
set
{
iID_m = value;
}
}
/// <summary>
/// Score db record
/// </summary>
[System.Xml.Serialization.XmlElement("ID",IsNullable = false)]
public object IDValue
{
get
{
return ID;
}
set
{
if (value == null)
{
ID = null;
}
else if (value is int || value is int?)
{
ID = (int)value;
}
else
{
ID = int.Parse(value.ToString());
}
}
}
XmlSerializer supports the ShouldSerialize{Foo}()
pattern, so you can add a method:
public bool ShouldSerializeID() {return ID.HasValue;}
There is also the {Foo}Specified
pattern - not sure if XmlSerializer supports that one.