Make an object that encapsulates List <> accessible through the [] operator?

I have a class that I did, it is basically an encapsulated List<> for a specific type. I can access List items using [] , as if it were an array, but I don't know how to make my new class inherit this ability from List<> . I tried to find this, but I’m sure I don’t know how to say what I want to do, and I haven’t found anything useful.

Thanks!

+4
source share
3 answers

This is called indexer :

 public SomeType this[int index] { get { } set { } } 
+9
source

This is called an indexer .

Indexers allow you to index instances of a class or structure in the same way as arrays. Indexers resemble properties, except that their Parameters.

  • Indexers allow you to index objects in the same way as arrays.

  • A get accessor returns a value. The accessory set assigns a value.

  • The this used to define indexers.

  • The value keyword is used to determine the value assigned by the index installer.

The following is an example EXAMPLE .

+1
source

There is already an indexer definition in the list, so there is no need to change this code. It will work by default.

  public class MyClass : List<int> { } 

And we can access the index here. Although we have not 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 is not intended to be inherited. You must encapsulate it without expanding it. - Service

And it will look like

 public class MyClass { private List<int> _InternalList = new List<int>(); public int this[int i] { get { return _InternalList[i]; } set { _InternalList[i] = value; } } } 
+1
source

All Articles