How to serialize/deserialize a nullable date

The time will come when you are serializing and deserializing object to and from XML that you will come across nullable dates, or more correctly an attribute XML date that is nullable.  If you are like me and using the System.Xml.Serialization namespace, which make the complete process of serializing and deserializing so much easier.

Here is the issue, the code below is a nullable datetime, which is fine in .NET

 

        private DateTime? dob;
        [XmlAttribute]
        public DateTime? DOB
        {
            get
            {
                return dob;
            }
            set
            {
                dob = value;
            }
        }

When you come the serialize/deserialize you find you get an error of:

System.InvalidOperationException: Cannot serialize member ‘DOB’ of type System.Nullable`1[System.DateTime]. XmlAttribute/XmlText cannot be used to encode complex types.

So to over come this you have a number of options, the one I have come up with is to pull the date in using a string and then pre-process the date and then store it in to the nullable date field, like this:

 

        private DateTime? dob;
        [XmlIgnore]
        public DateTime? DOB
        {
            get
            {
                return dob;
            }
            set
            {
                dob = value;
            }
        }

        [XmlAttribute(“DOB”)]
        public string DoBstring
        {
            get { 
                return DOB.HasValue
                ? XmlConvert.ToString(DOB.Value, XmlDateTimeSerializationMode.Unspecified)
                : string.Empty;
            }
            set { 
                DOB = 
                !string.IsNullOrEmpty(value)
                ? XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Unspecified)
                : (DateTime?) null;
            }
        }

You notice that the nullable Date field is not decorated with an XmlIgnore attribute, and the string is picking up the DOB attribute tag