Simple Program of Indexer in Console in ASP.NET using C#

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:

  1. 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.

  2. Polymorphism: Allows Polymorphism, which means the derived class can override a base class indexer.

  3. Uniqueness: Provides a signature that uniquely identifies an indexer.

  4. Non Static: Indexers cannot be static. If you declare indexer as static, the compiler will generate an error.

Here is the code for Indexer:

console application

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace Indexers  
  7. {  
  8.   
  9.   
  10.     class sample  
  11.     {  
  12.   
  13.   
  14.         string[] name = new string[3];  
  15.         public string this[int index]  
  16.         {  
  17.             get  
  18.             {  
  19.                 if (index < 0 || index >= name.Length)  
  20.                 {  
  21.                     return null;  
  22.                 }  
  23.                 else  
  24.                 {  
  25.                     return (name[index]);               
  26.                 }  
  27.             }  
  28.   
  29.             set   
  30.             {  
  31.                 name[index] = value;  
  32.               
  33.             }       
  34.         }  
  35.     }  
  36.     class Program  
  37.     {  
  38.         static void Main(string[] args)  
  39.         {  
  40.   
  41.             sample s = new sample();  
  42.             s[0]="Nilesh";  
  43.             s[1]="Purnima";  
  44.             s[2]="Chandni";  
  45.             for (int i = 0; i <= 2; i++)  
  46.               
  47.                 Console.WriteLine(s[i]);  
  48.             Console.ReadKey();  
  49.               
  50.         }  
  51.     }  
  52. }  
Output Of Indexers:

Output Of Indexers

Hope you like it. Have a nice day. Thank you for Reading.