Reputation: 835
I have a class that I made that is basically an encapsulated List<>
for a certain type. I can access the List items by using []
like if it was an array, but I don't know how to make my new class inherit that ability from List<>
. I tried searching for this but I'm pretty sure I don't know how to word correctly what I want to do and found nothing useful.
Thanks!
Upvotes: 4
Views: 125
Reputation: 98868
That's called an indexer.
Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.
Indexers enable objects to be indexed in a similar manner to arrays.
A get
accessor returns a value. A set
accessor assigns a value.
The this
keyword is used to define the indexers.
The value
keyword is used to define the value being assigned by the set indexer.
Here is an EXAMPLE.
Upvotes: 1
Reputation: 3069
List already have a definition for the Indexer so there is no need to change that code. It will work by default.
public class MyClass : List<int>
{
}
And we can access the indexer here. Even though we havent implemented anything
MyClass myclass = new MyClass();
myclass.Add(1);
int i = myclass[0]; //Fetching the first value in our list ( 1 )
Note that the List class isn't designed to be inherited. You should be encapsulating it, not extending it. – Servy
And this would look something like
public class MyClass
{
private List<int> _InternalList = new List<int>();
public int this[int i]
{
get { return _InternalList[i]; }
set { _InternalList[i] = value; }
}
}
Upvotes: 1