It sounds like the [DataMember]
is set against the field (or is defaulting to fields), and is bypassing the lazy behaviour. If you control the type, you could perhaps add an [OnSerializing]
method that peeks at this property before serialization kicks in... that way it should have a value, and you won't need to put code into other places.
If the type is generated, look to see if it is a partial class
. If so, you can add another partial class
of the same name (and same namespace), and put your [OnSerializing]
method in there...
Example (uncomment the last block to make it work):
using System;
using System.Runtime.Serialization;
using System.Xml;
class Program {
static void Main() {
using (XmlWriter writer = XmlWriter.Create(Console.Out)) {
new DataContractSerializer(typeof(Foo))
.WriteObject(writer, new Foo());
}
}
}
[DataContract]
partial class Foo {
[DataMember(Name="Bar")]
private int? bar;
public int Bar {
get {
if (bar == null) bar = 27; // somthing lazy
return bar.GetValueOrDefault();
}
set { bar = value; }
}
}
/* UNCOMMENT THIS
partial class Foo {
[OnSerializing]
private void BeforeSerialize(StreamingContext ctx) {
int tmp = Bar;
}
}
*/