blah blah blah is here! blah blah » Close

up0down
link

hi,
I need to create a collection that should have named indexes.
e.g.: In typical collection such as ArrayList :
ArrayList al= New ArrayList();
al.Add("10");
al.Add("20");
to access first element i have to use "0" in al[0]...such
I need to create a collection that has Named indexes instead of Numerical zero based indexes.
such as:
assume the collectio object is col1. to access the value element "RegoNo", i should use the collection object as col1["RegoNo"] or similar technique
Is this possible to do? If this is not possible then what would be a technique used for this?
cheers

last answered 10 months ago

1 answers

up0down
link

You'd need to create an accessible indexer property that takes in a string. You can use get and/or set accessors as needed.
e.g.,
public class MyCollection<T>
{
private Dictionary<string, T> items = new Dictionary<string, T>();
public T this[string key] //called "this" and using square brackets
{
get
{
return items[key];
}
set
{
items[key] = value;
}
}
public T this[int index] //you may overload the indexer too
{
get
{
return items.ElementAt(index);
}
}
}

up0down
link

THanks problem solved in another thread! : )

This post was imported from csharpfriends, if you have a similiar question please ask it again.

All previous members have been migrated, hope you enjoy the new platform!

Feedback