4

With the below two data members in a DataContract then using a DataContractSerializer, only Name is serialized as expected. My problem is when I deserialize the file. "Name" is read and loaded properly but as "Timeout" does not exist I would expect it to stay at the default of "TimeSpan.FromHours(12)". What infact happens is the DataContractSerializer assigns a value but as it has no value to assign it uses the timespan default of 0. Is there anyway around this behavour?

private string _name;
    [DataMember(Name = "Name")]
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name= value;
        }
    }

    private TimeSpan _timeout = TimeSpan.FromHours(12);
    public TimeSpan Timeout
    {
        get
        {
            return _timeout ;
        }
        set
        {
            _timeout = value;
        }
    }
Oli
  • 2,996
  • 3
  • 28
  • 50
  • How would a client have any knowledge of default values of non serialized members? Are you sharing the object definitions? – Dave Lawrence Jul 10 '12 at 16:41
  • This particular contract is strictly an in application contract used for caching certain metadata to disk so as to avoid having to poll a rest service over and over. The reason I want to leave some members out for now as it is moving into Beta and some options I want locked for now. – Oli Jul 10 '12 at 16:46
  • I don't think wcf supports writing or reading default values in the wsdl – Dave Lawrence Jul 10 '12 at 16:49
  • I'm not using WCF, just the DataContractSerializer. – Oli Jul 10 '12 at 16:54

1 Answers1

5

Is this your answer then

using OnDeserialized

[OnDeserialized]
void OnDeserialized(StreamingContext context)
{
    this._timeout = TimeSpan.FromHours(12);
}

from here Setting the initial value of a property when using DataContractSerializer

Community
  • 1
  • 1
Dave Lawrence
  • 3,843
  • 2
  • 21
  • 35
  • 5
    Worked Like a charm thanks-Except I had to use the attribute [OnDeserializing] to set the values before Serialization has started. Then the default values are overwritten if required. – Oli Jul 10 '12 at 17:12