Reputation: 37212
class Foo
{
public List<float> Data { get ; set ; } // list of numbers
private float Total { get ; set ; } // Contains sum of numbers in Data
// Constructors and other stuff.
}
My code that uses this class keeps modifying Data
so I want to see the relevant changes in Total
also.
I don't want to add function that recalculates Total
to the code that modifies Data
.
Example:
Foo f = new Foo(); // Total = 0
f.Data.Add(10); // Total = 10
f.Data.Add(30); // Total = 40
f[1] = 40; // Total = 50
// etc
So What is the solution to this problem ?
Upvotes: 0
Views: 2537
Reputation: 7526
Alter you get function to dynamically return the total instead (using linq is easiest):
private float Total
{
get
{
return Data.Sum();
}
}
No need for a set accessor really.
Upvotes: 2
Reputation: 7248
I think there is no need for the setter in the total property, however the getter simply recalculate the sum for every call
class Foo
{
public List<float> Data { get ; set ; } // list of numbers
private float Total { get{return Data.Sum()} ; } // Contains sum of numbers in Data
}
Upvotes: 1
Reputation: 2838
Add calculation logic to the Total getter:
private float Total
{
get { return CalculateResult(Data) };
}
This way you do not even need setter. Of course you can cache: introduce dirty flag in a class that is changed when you change Data list. Then cache calculation result that you get in Total getter to a local class field and reuse that if dirty flag is not set (clear it on recalculation).
Upvotes: 1
Reputation: 5299
Why do you need setter on Total
? The best way is to make Total auto-calculated property and calculate the Total's getter value dynamically.
Or... you can introduce private fields data
and total
and recalculate total
within Data
setter.
Upvotes: 0
Reputation: 68737
You are exposing the Data, it could all be erased at any time, I'd suggest the following:
class Foo
{
private List<float> _data = new List<float>();
public float Total {get; private set;}
public void Add(float f) { _data.Add(f); Total += f; }
}
Upvotes: 4
Reputation: 60276
I don't see the problem here. The Total
getter can compute the total of the list dynamically when it is being called, which does not modify the list at all. However, I don't see how you want to implement a setter for the total...
private float Total { // Contains sum of numbers in Data
get {
float total = 0;
foreach (float value in Data) {
total += value;
}
return total;
}
}
Upvotes: 4