Oli
Oli

Reputation: 3136

Default Values For Missing Data Members In DataContractSerializer

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;
        }
    }

Upvotes: 5

Views: 3004

Answers (1)

Dave Lawrence
Dave Lawrence

Reputation: 3929

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

Upvotes: 5

Related Questions