Difference between indexers / collections?

  • Thread starter Thread starter DKode
  • Start date Start date
D

DKode

Ok,

Consider the following example:

School Class
- StudentCollection Property

StudentCollection Class : CollectionBase
- Add
- Item
- Remove

Student Class
- Name Property
- Age Property

Now,

Up until this point, whenever I had a set of objects I needed to store
in a collection, I would make a class to handle all of the instances
of the objects (Student Class in this example), and then I would
return the collection to the Presentation layer to perform databinding
to controls. Also in the example above, whenever I would have a 0..*
class relationship I would create a private variable on the 0 side of
the relationship (School Class in this example). To hold my
collections, then I would expose this collection through a property in
School class so I could get only the students for that school back in
a nice neat collection.

Do indexers simplify this process for me or am I thinking about
indexers in the wrong way? The way I see it, indexers are a better way
of handling collections because you can refer to them on a key-value
basis instead of just a numerical index (like in collectionbase)

I guess i'm a little confused in the usability of indexers here. Could
someone clarify?

Thank you.
 
You can use CollectionBase on a Key, Value basis. Just add an overloaded
indexer that accepts a string instead of a int, but you have to be sure that
your key is unique!

public Student this[string name]
{
//iterate the List to find the right one or create a hash map when items
are added.
}


HTH;
Eric Cadwell
http://www.origincontrols.com
 
Eric,

I'm a little confused,

the peice of code you replied with there, would I add that overloaded
indexer to my class that derives from CollectionBase? and then I could
add/retrieve school instances like so:

School mySchool = new School();
SchoolCollection schoolColl = new SchoolCollection();

schoolColl[mySchool.Name] = mySchool;

Am i headed in the right direction here?
 
Yes, that encapsulates the looping or indexing logic in the collection class
and makes the rest of your code cleaner.

-Eric
 
Back
Top