What are Indexers?What is the use of it,and when to use Indexers?

Questions by harvenki

Showing Answers 1 - 7 of 7 Answers

mepoo

  • Jan 28th, 2007
 

An indexer is a member that enables an object to be indexed in the same way as an array.There are times when it is desirable to access a collection within a class as though the class itself were an array. For example, suppose you create a list box control named myListBox that contains alist of strings stored in a one-dimensional array, a private member variable named myStrings. Alist box control contains member properties and methods in addition to its array of strings.However, it would be convenient to be able to access the list box array with an index, just as if thelist box were an array.This can be achieved using the Indexer

  Was this answer useful?  Yes

Indexers are one neat feature of C#. They allow us to access a particular class as it is an array. They are similar to the properties in means that they encapsulate method calls into more convenient representation of value access and value setting. Declaring a property you can access it with its name, so it behaves like variable. The indexer is actually a class so it behaves as a type, i.e. you have to declare a variable of its type (actually to instantiate an object from it, but all variables are objects anyway). Indexers are also called smart arrays in C# and can be used to treat an object as an array. An indexer allows an instance of a class or a struct to be indexed as an array, which is useful for looping or iterating or data binding operations. The following is the syntax of an indexer declaration.
<Modifier> <Return type> this [arguments]

{
get
  {
  }
  Set
  {
  }
}
All indexers should accept at least one parameter. Indexers cannot be static. This is because static methods do not have access to ‘this’. The ‘this’ keyword indicates an instance of the current class.

  Was this answer useful?  Yes

baccha

  • Jul 20th, 2011
 

An indexer allows an instance of a class or a struct to be indexed as an array,which is useful for looping or iterating or data binding operations.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions