Indexer: Indexer can be termed as location indicators and they are used to access class objects in the same way as array elements are accessed.
Difference between Property and Indexers:
Property | Indexers |
Allows Identification by its Name. | Allows Identification by its Signature. |
Allows methods to be called as if they were public data members. | Allows elements of an internal collections or an object to be accessed by using an array notation on the object itself. |
Allows access through a simple name. | Allows access through an index. |
Uses Static or an Instance member | Uses an instance member only |
Contains the implicit value parameter | Contains the same formal Parameter list as the indexer. |
Indexers have the following feature:
- Inheritance: Allows Inheritance, which means a derived class can inherit a base class indexer. Modifier Such as virtual and override are used at the property level, not at the accessor level.
- Polymorphism: Allows Polymorphism, which means the derived class can override a base class indexer.
- Uniqueness: Provides a signature that uniquely identifies an indexer.
- Non Static: Indexers cannot be static. If you declare indexer as static, the compiler will generate an error.
Here is the code for Indexer:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace Indexers
- {
-
-
- class sample
- {
-
-
- string[] name = new string[3];
- public string this[int index]
- {
- get
- {
- if (index < 0 || index >= name.Length)
- {
- return null;
- }
- else
- {
- return (name[index]);
- }
- }
-
- set
- {
- name[index] = value;
-
- }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
-
- sample s = new sample();
- s[0]="Nilesh";
- s[1]="Purnima";
- s[2]="Chandni";
- for (int i = 0; i <= 2; i++)
-
- Console.WriteLine(s[i]);
- Console.ReadKey();
-
- }
- }
- }
Output Of Indexers:
Hope you like it. Have a nice day. Thank you for Reading.