Use collection of elements like an indexed array
-
I want to create my own collection of elements. I do it so:
public class MyCollectionName : IEnumerable
{
List<string> m_Collection = new List<string>();
// Some methods herepublic int Count { get { return m\_Collection.Count; } } public IEnumerator GetEnumerator() { return m\_Collection.GetEnumerator(); }
}
Is it possible to use instance of MyCollectionName like array and what should I change in MyCollectionName class for it? for example:
for(int i = 0; i < myCollectionInstance.Count; i++)
{
// And here use my collection as array
myCollectionInstance[i];
} -
I want to create my own collection of elements. I do it so:
public class MyCollectionName : IEnumerable
{
List<string> m_Collection = new List<string>();
// Some methods herepublic int Count { get { return m\_Collection.Count; } } public IEnumerator GetEnumerator() { return m\_Collection.GetEnumerator(); }
}
Is it possible to use instance of MyCollectionName like array and what should I change in MyCollectionName class for it? for example:
for(int i = 0; i < myCollectionInstance.Count; i++)
{
// And here use my collection as array
myCollectionInstance[i];
}yes, thats called an indexer; it is like a property that takes an integer argument. Example: public Record this[int index] { get {return (Record)currentRecords[index];} } gives the containing class a getter that returns an item of type Record. :)
Luc Pattyn [My Articles]
-
I want to create my own collection of elements. I do it so:
public class MyCollectionName : IEnumerable
{
List<string> m_Collection = new List<string>();
// Some methods herepublic int Count { get { return m\_Collection.Count; } } public IEnumerator GetEnumerator() { return m\_Collection.GetEnumerator(); }
}
Is it possible to use instance of MyCollectionName like array and what should I change in MyCollectionName class for it? for example:
for(int i = 0; i < myCollectionInstance.Count; i++)
{
// And here use my collection as array
myCollectionInstance[i];
} -
Add a default indexer:
public string this[int index] {
get { return m_Collection[index]; }
}--- single minded; short sighted; long gone;