So there's a few questions here. What do i return? what if it doesn't exist? should I use a for loop?
Firstly. A couple of good practises when attempting to find something which potentialy cannot be found.
1) Name the function with 'find' instead of 'get' as it implies the function behaviour. 'get' kind of implies that item exists and so the function should just go go and 'get' it. However 'find' implies some work may have to be done. A search maybe. Also the find may not be successful. This is useful when working with a team of programmers as they may not be intimately aware of what your code does. The programmer can read the function name and have an idea of whats going on.
2) The find may fail. This is a valid scenario. Write the code accordingly. Return false if the item is not found. On success output the found item as an output parameter.
So an example which may help your situation may be..
static void Main(string[] args)
{
Item[] allItems = new Item[100];
// make a test item with id of 45 and add it to the list
Item testItem = new Item(45);
allItems[testItem.ID] = testItem;
// find it
Item foundItem;
if (findItemById(allItems, 45, out foundItem) == true)
{
// Item was found !
}
}
static bool findItemById(Item[] itemStore, int id, out Item foundItem)
{
if( itemStore[id] != null )
{
foundItem = itemStore[id];
return true;
}
foundItem = null;
return false;
}
secondly, Should you use a loop to iterate and check?
I would say yes but the reason why and not how is probably more important.
To write the code ..
if (findItemById(allItems, 45, out foundItem) == true)
This is pretty straight forward. true on success. false on fail. founditem is set if success. You can write this once at the start of the project and it can easily be there at the end with no modifications.
However the findItemById() function offers a simple interface and can hide any implementation intricacies. So you can alter and optimise what it does throughout development. So if you use a list, and check for id's, if the list gets long and this function shows up on the profiler then you can hone in your optimisation time.
hope that helps :)