Creating a Collection Class

A

APA

I already have a colleciton class that implements IEnumerable but I also what to be able to
implement this inteface: MyCollectionClass["somestringkey"].

EX:

//MyCollectionClass is s collection of MyObject objects
MyObject mo = MyCollectionClass["somestringkey"];

or

string mypropertryvalue = MyCollectionClass["somestringkey"].SomeProperty


How do I implement the string key indexer in my collection class?



Thx.
 
M

Morten Wennevik

Hi APA

You can do this by adding a this-property to your class

public MyObject this[string key]
{
get
{
// look up the value
}
set
{
// set the value
}
}


I already have a colleciton class that implements IEnumerable but I also
what to be able to implement this inteface:
MyCollectionClass["somestringkey"].

EX:

//MyCollectionClass is s collection of MyObject objects
MyObject mo = MyCollectionClass["somestringkey"];

or

string mypropertryvalue =
MyCollectionClass["somestringkey"].SomeProperty


How do I implement the string key indexer in my collection class?



Thx.
 
S

sloan

In 1.1, you most often subclass CollectionBase.

Morten is correct, you want an indexer.

public MyObject this[string key]
{
get
{
// look up the value
}
set
{
// set the value
}
}

You can overload it also

public MyObject this[int idx]
{
get { return this.InnerList[idx];}//this is how you might do it
when I inherit from CollectionBase
{
// look up the value
}
set
{
// set the value
}
}

2.0 .. you will "switch out" to Generics usually.

spaces.msn.com/sholliday/

Find a referenece I make to Ludwig, and you'll find a nice article on
swapping out to generics, if you're at a 2.0 level.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top