0

My class uses a readonly WeakReference to store certain data. This class is also serializable via DataContract.

How should I handle the weak reference? I would like it to come back as empty (target null) after deserialization, just as if it had been collected.

Simply ignoring the issue is not possible because my code rightly expects the reference object itself to be non-null. Do I have to let go of the readonly and manually check for an re-create the weak reference object during uptime?

mafu
  • 31,798
  • 42
  • 154
  • 247

1 Answers1

1

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.)

dbc
  • 104,963
  • 20
  • 228
  • 340