Reputation: 47
I am looking to have an array property return the calculation of 2 other arrays at the same index (this has been answered using zip in another question Array property returns calculation of 2 other arrays). But now I have to set the value of the calculation.
public ushort[] LowLimit{ get; set; }
public ushort[] Range{ get; set; }
public ushort[] HiLimit => LowLimit.Zip(Range, (l,r) => (ushort)(l + r)).ToArray();
ie. if I set HiLimit[0], Range would be set to (value - LowLimit), how is this possible? Both getter and setter are required.
EDIT (2017-02-09): I have marked @dasblinkenlight answer as correct because its not possible. The reason I need this is because I am communicating with a device that sends a low limit and a range but the software allow the user to read and edit a low limit and high limit. The high and low limit are bound to controls on the display so I used properties for those and made two methods for setting and getting a range when communicating to the device.
public ushort[] LowLimit{ get; set; } = new ushort[8];
public ushort[] HighLimit{ get; set; } = new ushort[8];
public ushort getRange(int index) {
ushort range = 0;
if(index < 8)
range = (ushort)(HighLimit[index] - LowLimit[index]);
return range;
}
public void setRange(int index, ushort value) {
if (index < 8)
HighLimit[index] = (ushort)(LowLimit[index] + value);
}
Upvotes: 1
Views: 358
Reputation: 726479
Making a computed property bi-directional is not possible, because computed properties are always read-only. Moreover, when you expose properties that return arrays, you have no control over modifications performed on the arrays that your methods return: arrays are inherently mutable, with no way to "watch" over changes to their elements.
You can solve this issue by providing a method for setting HiLimit
, like this:
void SetHiLimit(int index, ushort newLimit) {
// Change `Range` as needed
}
Note: You may reconsider the use of computed property for the array, because it is recomputed every time that you access it. For example, if you have HiLimit
array of length 100, and you run a loop that accesses each element once, your code would recompute the array 100 times, creating 100 identical throw-away copies, with an overall asymptotic performance of O(n2).
Upvotes: 3