code_junkie

How do I overload the [] operator in C#

Nov 13th, 2011
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. class A
  2. {
  3. private List<int> values = new List<int>();
  4.  
  5. public int GetValue(int index)
  6. {
  7. return values[index];
  8. }
  9. }
  10.  
  11. public int this[int key]
  12. {
  13. get
  14. {
  15. return GetValue(key);
  16. }
  17. set
  18. {
  19. SetValue(key,value);
  20. }
  21. }
  22.  
  23. class SampleCollection<T>
  24. {
  25. private T[] arr = new T[100];
  26. public T this[int i]
  27. {
  28. get
  29. {
  30. return arr[i];
  31. }
  32. set
  33. {
  34. arr[i] = value;
  35. }
  36. }
  37. }
  38.  
  39. // This class shows how client code uses the indexer
  40. class Program
  41. {
  42. static void Main(string[] args)
  43. {
  44. SampleCollection<string> stringCollection =
  45. new SampleCollection<string>();
  46. stringCollection[0] = "Hello, World";
  47. System.Console.WriteLine(stringCollection[0]);
  48. }
  49. }
  50.  
  51. public int this[int index]
  52. {
  53. get
  54. {
  55. return GetValue(index);
  56. }
  57. }
  58.  
  59. public int this[int index]
  60. {
  61. get
  62. {
  63. return GetValue(index);
  64. }
  65.  
  66. set
  67. {
  68. SetValue(index, value);
  69. }
  70. }
  71.  
  72. public int this[string index]
  73. ...
  74.  
  75. public int this[int index]
  76. {
  77. return values[index];
  78. }
Add Comment
Please, Sign In to add comment