Hi,
I've seen collections where elements can be accessed using different 'keys' or accessors in an overloaded array sort of way. Let me show you what I mean:
MyCollection[3] would get the 4th object in the collection
MyCollection["title"] would get the object with a title of 'title'
MyCollection[SomeObj] would get the object with the matching SomeObj
I'm not sure how this is done; through some type of extended collection or using some type of interface. Does anyone have any simple examples of doing this? Or any suggestions on what I might be trying to do?
Many thanks,
Rob
Loading
Bechir BejaouiPosted Jun 3, 2008, 7:47 PM
supose that you want to create your customized container object witch called MyCollection that contains ints
If you are using the classic way (without generics)
using System.Collection;
public class MyCollection
{
private ArrayList list;
public MyCollection() { list = new ArrayList(); }
public int this[int Index]
{
get { return (int)list[Index]; }
set { list[Index] = value; }
}
public int this[string ID]
{
get { return (int)list[ID]; }
set { list[ID] = value; }
}
............
}
If you are using the new way (with generics) introduced within the 2.0 version here you is the code
class MyCollection
{
private T[] arr;
public MyCollection(int Dimension)
{
arr = new T[Dimension];
}
public T this[int Index]
{
get
{
return arr[Index];
}
set
{
arr[Index] = value;
}
}
public T this[string ID]
{
get
{
return arr[ID];
}
set
{
arr[ID] = value;
}
}
....
}
Jan MontanoPosted Jun 3, 2008, 5:17 AM
Creating Your Own Collections
Dipal ChoksiPosted Jun 3, 2008, 5:08 AM