What to use instead of shared computed property?

I have a class with three properties:

amount as double
percentage as double
total as double

amount is a computed property which automatically adds the amount to the total: total = total + mamount

total is a shared property as it is the running total across all instances

Now when total changes then percentage has to change for all instances as well.

Would have been nice if I could have made total a shared computed property that updates all percentages like this: percentage = amount *100 / mtotal

Unfortunately “shared computed property accessors cannot access instance properties”

Of course I could keep a list of all the instances and iterate over the list to update all the percentages, but is there a more elegant way of doing this?

TIA

Markus

Shared methods/properties know nothing about a specific instance…

Use a shared Factory Method in conjunction with a private constructor (so instances can only be created by the factory method) to create an instance and have the factor method register it with a Private Shared array. Create a destructor for the class that removes it from that Array.

Shared methods/computed properties could then work on the array to do calculations

[code]Class SomeName

Private mAmount As Double

Property Amount As Double
Get
Return mAmount
End Get
Set
mAmount = value
sTotal = sTotal + value
End Set
End Property

Property Percentage As Double
Get
Return mAmount / sTotal * 100
End Get
End Property

Private Shared sTotal As Double
?
Shared Property Total As Double
Get
Return sTotal
End Get
End Property

End Class[/code]
Caution:

  • With the Double data type you will get in trouble, you’re probably better of using Currency or Integer for (currency) amounts.
  • With that kind of solution you can’t have more than one “sets” of instances, since sTotal is like a global property. This means you can’t use it in two different windows for example.

Check this https://drive.google.com/file/d/0B6w6JZen_vW2M1E0bHlzemgtejA/edit?usp=sharing

[quote=116656:@Eli Ott] Property Percentage As Double Get Return mAmount / sTotal * 100 End Get End Property.[/quote]

Ah, yes - I see where I went wrong. I tried to set the percentage for later use but that is unnecessary.

[quote]Caution:

  • With the Double data type you will get in trouble, you’re probably better of using Currency or Integer for (currency) amounts.
  • With that kind of solution you can’t have more than one “sets” of instances, since sTotal is like a global property. This means you can’t use it in two different windows for example.[/quote]

It’s not currency but amount of peptide :wink: but the point is well taken.

Good point on the different windows.

Thanks!