Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 232
MPelletier Avatar asked Jun 03 '26 23:06

MPelletier


1 Answers

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;
like image 184
Rekha G Avatar answered Jun 05 '26 12:06

Rekha G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!