Since the data contract serializers do not call the default constructor (or any other constructor), you may need to let go of the readonly
. You could make this somewhat palatable by hiding the field in a get-only property like so:
public class MyClass
{
WeakReference _m_private_reference_do_not_use_directly;
WeakReference Reference
{
get
{
if (_m_private_reference_do_not_use_directly == null)
Interlocked.CompareExchange(ref _m_private_reference_do_not_use_directly, new WeakReference(null), null);
return _m_private_reference_do_not_use_directly;
}
}
}
The other option would be to short-circuit data contract serialization for your class by making it implement ISerializable
and then allocating the WeakReference
in the protected MyClass(SerializationInfo info, StreamingContext context)
constructor. But in this case I reckon the cure might be worse than the disease.
DataContractSerializer
does support OnDeserializedAttribute
callback methods, so you could allocate the weak reference there instead of checking for null every time. However, you would still need to let go of the readonly
.
(All this assumes that you don't want to store the weakly referenced data when present.)