Tuesday 20 July 2010

Serializing a DateTime

I had an issue a few days ago about how to serialize a DateTime structure, as for some unbeknownst reason this is not supported by .NET. The solution was simple however, just wrap the DateTime in a class that you can serialize. We use the nifty little XmlIgnore attribute to tell the serializer to ignore our DateTime, but provide a separate string we can use to pickle and then unpickle the value.

[Serializable]
public class SerializableDateTime
{
    [XmlIgnore]
    public DateTime Value
    {
        get;
        private set;
    }

    // This is the value that actually gets serialized.
    public string SerializationValue
    {
        get
        {
            return Value.ToString();
        }
        
        set
        {
            Value = DateTime.Parse(value);
        }
    }

    public SerializableDateTime()
    : this(new DateTime())
    { }

    public SerializableDateTime(DateTime value)
    {
        Value = value;
    }
}

No comments:

Post a Comment