After further pondering the implications of DataContractSerializer not calling constructors or static field initializers, it seems like a cleaner design pattern to have properties self-initialize like this:
private ObservableCollection<object> myObjects;
public ObservableCollection<object> MyObjects
{
get
{
if (myObjects == null) myObjects = new ObservableCollection<object>();
return myObjects;
}
set
{
myObjects = value;
}
}
as opposed to providing two initialization paths like this:
public MyClass()
{
InitializeClass();
}
[OnDeserialized()]
private void OnDeserialized(StreamingContext c)
{
InitializeClass();
}
private void InitializeClass()
{
// Note here I can still use a field.
// Self-initialization requires a property.
myObjects = new ObservableCollection<objects>();
}
My main concern is that the latter pattern will not fail unit tests that construct the class with new
should the special OnDeserialized
initialization be forgotten, unless those unit tests are specifically designed to have knowledge that they may be used with DataContractSerializer
at some point.
That feels too entangled.
One downside of the self-initialization approach is that it requires properties rather than fields (since field initializers are ignored by DataContractSerializer
).
Are there other downsides that I am not considering?