Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make object that encapsulates List<> accessable via [] operator?

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!

like image 454
Mr. Adobo Avatar asked Dec 20 '22 09:12

Mr. Adobo


2 Answers

That's called an indexer:

public SomeType this[int index] {
    get { }
    set { }
}
like image 173
SLaks Avatar answered Mar 08 '23 23:03

SLaks


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; }
    }
}
like image 24
Evelie Avatar answered Mar 09 '23 01:03

Evelie