Imagine an object you are working with has a collection of other objects associated with it, for example the Controls collection on a WinForm. You want to check for a certain object in the collection, but the collection doesn't have a Contains() method. There are several ways of dealing with this.
- Implement your own Contains() method by looping through all items in the collection to see if one of them is what you are looking for. This seems to be the "best practice" approach.
- I recently came across some code where instead of a loop, there was an attempt to access the object inside a try statement, as follows:
try { Object aObject = myCollection[myObject]; } catch(Exception e) { //if this is thrown, then the object doesn't exist in the collection }
My question is how poor of a programming practice do you consider the second option be and why? How is the performance of it compared to a loop through the collection?