Creating a Collection Class

  • Thread starter Thread starter APA
  • Start date Start date
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.
 
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.
 
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.
 
Back
Top