XML deserialization - throwing custom errors
See the question and my original answer on StackOverflowThe "Input string was not in a correct format" messages comes from a standard System.FormatException
raised by a call to int.Parse
, added to the automatically generated assembly that does the deserialization. I don't think you can add some custom logic to that.
One solution is to do something like this:
[XmlElement("IntField")]
[Browsable(false)] // not displayed in grids
[EditorBrowsable(EditorBrowsableState.Never)] // not displayed by intellisense
public string IntFieldString
{
get
{
return DoSomeConvert(IntField);
}
set
{
IntField = DoSomeOtherConvert(value);
}
}
[XmlIgnore]
public int? IntField { get; set; }
It's not perfect, because you can still get access to the public IntFieldString
, but at least, the "real" IntField
property is used only programmatically, but not by the XmlSerializer (XmlIgnore
), while the field that's holding the value back & forth is hidden from programmers (EditorBrowsable
), grids (Browsable
), etc... but not from the XmlSerializer
.