I have (lots of) objects Foo with an unique ID and want to store these in a Dictionary. The dictionary key in C# can be any primitive type or object. I could use the integer foo1.ID as key but also the object foo1.
Which is the correct way of implementing that and is there a difference in performance using either the ID (an integer) or the object as key?
NB. The values in the dictionary are other (type of) of objects.
How do you intend to search the dictionary? If you intend to search for items within the dictionary based purely on
ID, then use that as the key. OTOH, if you’re going to have an instance of aFoo, then make that the key.Re: your edit – now we know that the
Foois either “the key” or “the object that provides the key value by accessing a property”, then it seems simple to say, use aDictionary<Foo,OtherClass>– assuming you’ve set up equality comparisons onFooobjects appropriately – why force every instance of lookup to know to extract a specific property from theFooobjects?