In this article, I am going to share with you about Indexer in C#
What is Indexer?
- Indexer is used for treating objects as an array.
- Indexer is a property that allows instances of class or struct to be indexed similar to an array.
- Indexer is also known as a smart array, or one can say indexer as Parameterized property.
- With Indexer, class or struct instances can be accessed using [] array access operator.
- Indexer makes the syntax-syntactic sugar. Means make code concise and easy to understand.
- Indexer uses 'get' and 'set' accessor similar to property. 'get' accessor returns a value. 'set' accessor set a value. The 'value' keyword used to define the value being assigned by the 'set' accessor.
Syntax of Indexer is,
- <access_modifier> <return_type> this [<Parameters_list>]
- {
- //Implementation of get and/or set accessor
- }
Here, access_modifier can be public, private, protected or internal return_type can be any valid return type(int, string, bool etc) other than void Parameters_list must contain one or more than one parameter.
Example
- public int this[int x]
- {
- get { return x; }
- set { value = x; }
- }
- Indexer name must be 'this' keyword.
- Indexer can be public, private, protected or internal.
- Indexer can be used when a class represents a list, collection or array of objects.
Code
Here, in the below problem, we have created an indexer in class 'Main'. With indexer, we are putting and retrieving values to an array of int type. Indexer uses get and set accessor to get and set value from/to the array. Indexer name should be 'this'. Inside class 'Program', we have created an object of class 'Main' and that object is now working similar to an array. The reason is one and only indexer. Indexer allows the object to be treated as an array as shown in the program. Index on which value is not assigned will be by default set to 0.
- using System;
- using System.Collections.Generic;
- using System.Linq;
-
- namespace Tutpoint
- {
- class Main
- {
-
- public int[] int_array = new int[10];
-
-
- public int this[int x]
- {
- get
- {
- return int_array[x];
- }
- set
- {
- int_array[x] = value;
- }
- }
- }
-
- class Program
- {
-
- static void Main(string[] args)
- {
- Main main = new Main();
-
-
- main[0] = 222;
- main[8] = 33;
- main[6] = 11;
- main[2] = 1;
- main[3] = 6;
- for (int i = 0; i < main.int_array.Length; i++)
- {
- Console.WriteLine(main.int_array[i]);
- }
- Console.ReadLine();
- }
- }
- }
Output
Note
Here for this program, we have to use index between 0 to 9 according to the size of an array else runtime 'IndexOutOfRangeException' will generate as "Index was outside the bounds of the array".
Some of the examples,
main[-3] = 6;
main[93] = 60;
- Indexer can be overloaded means that a class can contain more than one indexer but with different parameters.
In the below program, we have created 3 indexers with different parameters. An object created of the class 'Main' then be used with proper arguments and accordingly Indexer will be called. This is similar to method overloading.
Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
-
- namespace Tutpoint
- {
- class Main
- {
- public int[] int_array = new int[10];
-
-
- public int this[int x]
- {
- get
- {
- return int_array[x];
- }
- set
- {
- int_array[x] = value;
- }
- }
-
-
- public int this[int x, string str]
- {
- get
- {
- return int_array[x];
- }
- set
- {
- if (str != null)
- int_array[x] = str.Length;
- else
- int_array[x] = value;
- }
- }
-
-
- public int this[int x, bool b]
- {
- get
- {
- return int_array[x];
-
- }
- set
- {
- if (b)
- int_array[x] = value;
- else
- int_array[x] = 1;
- }
- }
-
- }
-
- class Program
- {
-
- static void Main(string[] args)
- {
- Main main = new Main();
- main[1] = 10;
- main[2] = 20;
- main[3] = 30;
- main[4, "john"] = 40;
- main[5, "Player rock"] = 50;
- main[6, "Snow the Bastard!!"] = 60;
- main[7, true] = 70;
- main[8, false] = 80;
- main[0, true] = 0;
- main[9, false] = 90;
-
- for (int i = 0; i < main.int_array.Length; i++)
- {
- Console.WriteLine(main.int_array[i]);
- }
-
- Console.ReadLine();
- }
- }
- }
Output
- 0
- 10
- 20
- 30
- 4
- 11
- 18
- 70
- 1
- 1
Note
If we create 2 indexers with same parameters of the same type in the same sequence but different return type the compiler will generate an error as "Type 'Main' already defines a member called 'this' with the same parameter types".
-
- public int this[int x]
- {
- get
- {
- return 100;
- }
- set
- {
- x = value;
- }
- }
-
-
-
- public string this[int x]
- {
- get
- {
- return "john";
- }
- set
- {
- x = Convert.ToInt32(value);
- }
- }
Can't-Do Activities
Static keyword cannot be used with indexers.
If we use 'static' keyword with indexer then the compiler will produce a compile time error as "The modifier 'static' is not valid for this item"
-
- public static int this[int x]
- {
- get { return x; }
- set { value = x; }
- }
Indexer must contain at least one parameter.
If indexer does not contain any parameter then the compiler will produce a compile time error as "Indexers must have at least one parameter"
-
- public int this[]
- {
- get { return x; }
- set { value = x; }
- }
Indexer must have a valid return type other than void.
If we use indexer of void type then the compiler will produce a compile time error as "Indexers cannot have void type"
-
- public void this[int x]
- {
- get { return x; }
- set { value = x; }
- }
'
ref' and '
out' keywords cannot be used with indexers.
If we use 'ref' and 'out' keywords on indexer then the compiler will produce a compile time error as "ref and out are not valid in this context"
-
- public string this[ref string x, int y, out int z]
- {
- get
- {
- return "john";
- }
- set
- {
- x = value;
- }
- }
Name attribute is used to define Indexer with a name.
- [System.Runtime.CompilerServices.IndexerName("Main")]
- public string this[string x]
- {
- }
Difference between Indexer and Property
- Indexer is created with 'this' keyword while Property doesn't require 'this' keyword.
- Indexer is identified by signature while Property is identified with their name.
- Indexer is accessed using indexes while Property is accessed with their name.
- Indexer cannot be static while Property can be static.
- 'get' accessor of an indexer has parameter list while 'get' accessor of a property has no parameters.
- 'set' accessor of an indexer has parameter list in addition to the value parameter while 'set' accessor of a property contains value parameter only.
- Indexer can be overloaded while property cannot be overloaded.
Conclusion
An indexer is a syntactic sugar which makes code concise and easy to understand. An indexer is good to use when we are dealing with either of them(array, list, collection etc.). I hope this article helps you to understand a bit more about Indexers.
Thank you. Please feel free to ask any question or make a suggestion. You can read my other articles or blogs on this link.
C# Articles