If in a class you have a value type property that is optional, it's common to specify it as nullable. However, if you serialize a nullable value type property to XML, you'll get something like this if it's null.
<Value xsi:nil="true" />
Or, if you turned off declaration of the XML schema instance namespace, it will be even more verbose.
<Value p2:nil="true" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance" />
This might look strange but it will properly deserialize. Nonetheless, you might have a reason to have a nullable value type property serialize the way a class property does, which is to not appear in the XML output at all if it's null. Setting the IsNullable property of the XmlElement attribute for such a property will have no effect. (Well, setting it to false will result in a run-time error.)
The XmlElementAttribute.IsNullable Property page at MSDN has this to say.
You cannot apply the IsNullable property to a member typed as a value type because a value type cannot contain null. Additionally, you cannot set this property to false for nullable value types. When such types are null, they will be serialized by setting xsi:nil to true.
One work-around is to declare another property that is a class type, such as string, and parse it in the nullable value property.
[XmlElement("Value")]
public string ValueString { get; set; }
[XmlIgnore]
public int? Value
{
get { return int.Parse(ValueString); }
set { ValueString= value.ToString(); }
}
Of course, you can go in the opposite direction as well.
[XmlElement("Value")]
public string ValueString
{
get { return Value.HasValue ? Value.Value.ToString() : null; }
set
{
if(value != null)
Value= int.Parse(value);
else
Value= null;
}
}
[XmlIgnore]
public int? Value { get; set; }