Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Generics - List<> - returning a value 2

Status
Not open for further replies.

golcarlad

Programmer
Nov 23, 2004
232
GB
I have a generic list holding objects, some of which are of a different type but inherit from the same abstract base class - on occassion I would like to retrieve from the list a specific object of a particular type, is there a way to do this, in a nice simple way?
 
1. generally, you use base classes (and interfaces) because at the level you're dealing with the base class, you don't care what derived class something is (in order to drive a car i just need to know that it's drivable, not how many wheels or doors it has).
if you want an instance to behave differently, you override the functionality on the derived class.

Code:
// best practice
foreach ( BaseClass item in list )
{
 // each derived class has Method() and Property overridden to do appropriate things
 if ( item.Property )
 {
  item.Method();
 }
}

// sub-optimal
// ie you could do this but should try to think harder
foreach ( BaseClass item in list )
{
 DerivedClass derived = item as DerivedClass;
 if ( derived != null )
 {
   ExternalMethodOnDerivedClass(derived);
   derived.DerivedSpecificMethod();
 }
}

2. lists are pretty dumb: you pretty much have to iterate over the whole list if you want to retrieve an item by anything other than its index; if you want a specific item, use a dictionary.


mr s. <;)

 
Yeh, I think Dictionary is the way to go here - I think it would overcomplicate an object if all I have to do is leverage the power of the Dictionary i.e. something that has already been designed with what I need to the job.

Sometimes I forget about the usefulness of Dictionaries, or sometimes feel that you can lean on them too much to base your code around, but in this case I think its use is appropriate. Thanks for some interesting feedback.
 
lists are pretty dumb: you pretty much have to iterate over the whole list if you want to retrieve an item by anything other than its index;

That's like saying a car is dumb because you can't drive it overseas... so a boat is better...

Dictionary and List have 2 very different purposes.

A dictionary is for a lookup - a "what is this item related to?"

A list is a pile of items that need to be sorted or displayed. You wouldn't hand a dictionary in to a school teacher and say your essay is made up or the words from the dictionary in the following order... :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top