I have such class (sorry about posible mistakes, i’m writing it right here.) Class is simplified for this example, it must be more complex of course.
class SP500Index {
SP500Index(List<OrderBook> stocks) {
foreach (var stock in stocks) {
stock.StockUpdated += stockUpdated; // how to handle?
}
}
}
So I have a lot of sources and I need to handle StockUpdated event from them. In handler I need to know index of stock in stocks list which raised the event. How to do that?
upd for perfomance reasons I don’t want “sender look-up” instead I want index. Lookup is not trivial operation and likely involves Hashcode calculation Equals method call etc. Imagine how ofthen SP500 index changes…
If your benchmark shows that you need the index when the event occurs you can add the index as a property to
OrderBookand when you add an element to the list, set this property. This value will be available to the event handler.This will work assuming that you keep the
OrderBookobjects in a singleListand do not do any rearranging of this original list. If you have multiple lists with each object stored on only one of those lists, then you could add anOwnerproperty that references the list that it is stored on.For example…
When you build
List<OrderBook>:Or better, use a helper for managing the list that cares for the book keeping of the index update:
The updated
OrderBook:And then an sample event handler using this index:
What is your reason for having that index? Everything you need should be in the object. If you use this to manipulate the original list (such as removing this item from the list) then you have the problem of recomputing the saved index of all the previously stored objects.
If you are maintaining a parallel list with other objects, then you perhaps should consider a different design.