Search code examples
c#deserializationxml-deserialization

Automatic post-deserialization execution


Suppose a simple class in C#:

[Serializable]
public class MyClass
{
    public int A { get; set; }
    public int B { get; set; }
    [XmlIgnore]
    public int Sum { get; }
}

This is deserialized from a simple XML file containing values for A and B. However, Sum is calculated with A and B, not serialized. Assume that I don't want to calculate Sum on the fly in the accessor. How can I pre-calculate Sum? The constructor is called first, naturally, meaning A and B not asigned later, and thus are no use yet to calculate Sum. Is there some kind of post-deserialization or post-instanciation thingie I could use so that the object is completely created in one step? I just don't want my objects to ever be in an incomplete and invalid state.


Solution

  • I think you are trying to ask something else. This use case does not justify the complexity of solution you are asking for.

    If this is the use case:

    1. Calculate on the fly. Turn Sum into a method.
    2. Use backing fields if you are concerned about overhead.

    e.g.

    if (_alreadyCalculated) 
    {
        return _sum;
    }
    _sum = A+B;
    _alreadyCalculated = true;
    return _sum;