Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger function on deserialization

I have a class with a number of fields which are normally calculated in the constructor from other data in the class. They are not serialized to XML because any changes to the rest of the data will likely require their recalculation.

Is there a way I can set up a function call to be triggered on deserialization?

like image 971
Tom Savage Avatar asked May 24 '10 10:05

Tom Savage


2 Answers

What you are describing is [OnDeserialized]

XmlSerializer does not support serialization callback methods (at least, not in MS .NET; mono may be different). Depending on your needs, you could try DataContractSerializer which does support serialization callbacks (as do a number of other serializers). Otherwise, your best approach may be to just have your own public method that you call manually.

Another option is to manually implement IXmlSerializable, but this is hard.

like image 162
Marc Gravell Avatar answered Oct 16 '22 09:10

Marc Gravell


Since an object that can be XML serialized need a public parameterless constructor, it seems you have a hole in your class design even before you hit XML serialization.

Personally I would go with lazy calculation of those fields. Store a flag inside the class whether you have calculated the fields or not, and set that field to a value signifying "out of date" when any of the properties that are used in the calculation is changed. Then, in the properties that return the calculated values, check if you need to recalculate before returning the value.

This would then work regardless of XML serialization or not.

example:

[XmlType("test")]
public class TestClass
{
    private int _A;
    private int? _B;

    public TestClass()
        : this(0)
    {
    }

    public TestClass(int a)
    {
        _A = a;
    }

    [XmlAttribute("a")]
    public int A
    {
        get { return _A; }
        set { _A = value; _B = null; }
    }

    [XmlIgnore]
    public int B
    {
        get { if (_B == null) Recalculate(); return _B; }
        set { _B = value; }
    }

    private void Recalculate()
    {
        _B = _A + 1;
    }
}
like image 26
Lasse V. Karlsen Avatar answered Oct 16 '22 10:10

Lasse V. Karlsen