INDEXER IN C#

C# introduces a new concept Indexer. This is very useful for some situation. Let as discuss something about Indexer.
  • Indexer Concept is object act as an array.
  • Indexer an object to be indexed in the same way as an array.
  • Indexer modifier can be private, public, protected or internal.
  • The return type can be any valid C# types.
  • Indexers in C# must have at least one parameter. Else the compiler will generate a compilation error.
  1. this [Parameter]
  2. {
  3. get
  4. {
  5. // Get codes goes here
  6. }
  7. set
  8. {
  9. // Set codes goes here
  10. }
  11. }
For Example
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Indexers
  5. {
  6. class ParentClass
  7. {
  8. private string[] range = new string[5];
  9. public string this[int indexrange]
  10. {
  11. get
  12. {
  13. return range[indexrange];
  14. }
  15. set
  16. {
  17. range[indexrange] = value;
  18. }
  19. }
  20. }
  21. /* The Above Class just act as array declaration using this pointer */
  22. class childclass
  23. {
  24. public static void Main()
  25. {
  26. ParentClass obj = new ParentClass();
  27. /* The Above Class ParentClass create one object name is obj */
  28. obj[0] = "ONE";
  29. obj[1] = "TWO";
  30. obj[2] = "THREE";
  31. obj[3] = "FOUR ";
  32. obj[4] = "FIVE";
  33. Console.WriteLine("WELCOME TO C# CORNER HOME PAGE\n");
  34. Console.WriteLine("\n");
  35. Console.WriteLine("{0}\n,{1}\n,{2}\n,{3}\n,{4}\n", obj[0], obj[1], obj[2], obj[3], obj[4]);
  36. Console.WriteLine("\n");
  37. Console.WriteLine("ALS.Senthur Ganesh Ram Kumar\n");
  38. Console.WriteLine("\n");
  39. Console.ReadLine();
  40. }
  41. }
  42. }