Setting the initial value of a property when using DataContractSerializer
Posted
by Eric
on Stack Overflow
See other posts from Stack Overflow
or by Eric
Published on 2010-04-28T00:01:29Z
Indexed on
2010/04/28
0:03 UTC
Read the original article
Hit count: 393
If I am serializing and later deserializing a class using DataContractSerializer how can I control the initial values of properties that were not serialized?
Consider the Person class below. Its data contract is set to serialize the FirstName and LastName properties but not the IsNew property. I want IsNew to initialize to TRUE whether a new Person is being instantiate as a new instance or being deserialized from a file.
This is easy to do through the constructor, but as I understand it DataContractSerializer does not call the constructor as they could require parameters.
[DataContract(Name="Person")]
public class Person
{
[DataMember(Name="FirstName")]
public string FirstName { get; set; }
[DataMember(Name = "LastName")]
public string LastName { get; set; }
public bool IsNew { get; set; }
public Person(string first, string last)
{
this.FirstName = first;
this.LastName = last;
this.IsNew = true;
}
}
© Stack Overflow or respective owner