Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a class that (like array) can be indexed with `arr[key]`?

Like we do Session.Add("LoginUserId", 123); and then we can access Session["LoginUserId"], like an Array, how do we implement it?

like image 869
Riz Avatar asked Jul 24 '11 14:07

Riz


People also ask

Can an array be indexed?

Every variable in MATLAB® is an array that can hold many numbers. When you want to access selected elements of an array, use indexing. Using a single subscript to refer to a particular element in an array is called linear indexing.

How are array elements indexed?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

What is array index with example?

An array is an ordered list of values that you refer to with a name and an index. For example, consider an array called emp , which contains employees' names indexed by their numerical employee number. So emp[0] would be employee number zero, emp[1] employee number one, and so on.

What is indexers in C# with example?

Indexers allow instances of a class or struct to be indexed just like arrays. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters.


2 Answers

You need an indexer:

public Thing this[string index] {     get     {          // get the item for that index.          return YourGetItemMethod(index)     }     set     {         // set the item for this index. value will be of type Thing.         YourAddItemMethod(index, value)     } } 

This will let you use your class objects like an array:

MyClass cl = new MyClass(); cl["hello"] = anotherObject; // etc. 

There's also a tutorial available if you need more help.

Addendum:

You mention that you wanted this to be available on a static class. That get's a little more complicated, because you can't use a static indexer. If you want to use an indexer, you'd need to access it off of a static Field or some such sorcery as in this answer.

like image 120
jakebasile Avatar answered Sep 22 '22 17:09

jakebasile


You should use indexers See the link: http://msdn.microsoft.com/en-us/library/2549tw02.aspx

like image 25
Mohammed Asaad Avatar answered Sep 24 '22 17:09

Mohammed Asaad