How to use [] operator directly on object with indexer in C#

1 Answer

0 votes
using System;

class Student
{
  private string[] names = new string[10];

  public string this[int index]
  {
    get {
      return this.names[index];
    }
    set {
      this.names[index] = value;
    }
  }
}

class Program
{
  static void Main(string[] args)
  {
    Student s = new Student();

    s[0] = "Dumbledore";
    s[1] = "Rubeus";
    s[2] = "Hermione";

    Console.WriteLine(s[0]);
    Console.WriteLine(s[1]);
    Console.WriteLine(s[2]);
  }
}



/*
run:

Dumbledore
Rubeus
Hermione

*/

 



answered Dec 19, 2020 by avibootz

Related questions

1 answer 130 views
1 answer 119 views
119 views asked Jan 15, 2017 by avibootz
1 answer 118 views
118 views asked Apr 27, 2017 by avibootz
1 answer 114 views
114 views asked Jan 5, 2017 by avibootz
1 answer 116 views
...