How do I overload the [] operator in C#?

CsharpServer Side ProgrammingProgramming

<p>The [] operator is called an indexer.</p><p>An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. You can then access the instance of this class using the array access operator ([ ]).</p><p>Indexers can be overloaded. Indexers can also be declared with multiple parameters and each parameter may be a different type. It is not necessary that the indexes have to be integers.</p><h2>Example 1</h2><pre class="prettyprint notranslate">static void Main(string[] args){ &nbsp; &nbsp;IndexerClass Team = new IndexerClass(); &nbsp; &nbsp;Team[0] = &quot;A&quot;; &nbsp; &nbsp;Team[1] = &quot;B&quot;; &nbsp; &nbsp;Team[2] = &quot;C&quot;; &nbsp; &nbsp;Team[3] = &quot;D&quot;; &nbsp; &nbsp;Team[4] = &quot;E&quot;; &nbsp; &nbsp;Team[5] = &quot;F&quot;; &nbsp; &nbsp;Team[6] = &quot;G&quot;; &nbsp; &nbsp;Team[7] = &quot;H&quot;; &nbsp; &nbsp;Team[8] = &quot;I&quot;; &nbsp; &nbsp;Team[9] = &quot;J&quot;; &nbsp; &nbsp;for (int i = 0; i &lt; 10; i++){ &nbsp; &nbsp; &nbsp; Console.WriteLine(Team[i]); &nbsp; &nbsp;} &nbsp; &nbsp;Console.ReadLine(); } class IndexerClass{ &nbsp; &nbsp;private string[] names = new string[10]; &nbsp; &nbsp;public string this[int i]{ &nbsp; &nbsp; &nbsp; get{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return names[i]; &nbsp; &nbsp; &nbsp; } set { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;names[i] = value; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} }</pre><h2>Output</h2><pre class="result notranslate">A B C D E F G H I J</pre><h2>Example 2</h2><h3>Overriding []</h3><pre class="prettyprint notranslate" style="">static class Program{ &nbsp; &nbsp;static void Main(string[] args){ &nbsp; &nbsp; &nbsp; IndexerClass Team = new IndexerClass(); &nbsp; &nbsp; &nbsp; Team[0] = &quot;A&quot;; &nbsp; &nbsp; &nbsp; Team[1] = &quot;B&quot;; &nbsp; &nbsp; &nbsp; Team[2] = &quot;C&quot;; &nbsp; &nbsp; &nbsp; for (int i = 0; i &lt; 10; i++){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(Team[i]); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; System.Console.WriteLine(Team[&quot;C&quot;]); &nbsp; &nbsp; &nbsp; Console.ReadLine(); &nbsp; &nbsp;} } class IndexerClass{ &nbsp; &nbsp;private string[] names = new string[10]; &nbsp; &nbsp;public string this[int i]{ &nbsp; &nbsp; &nbsp; get{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return names[i]; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; set{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;names[i] = value; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} &nbsp; &nbsp;public string this[string i]{ &nbsp; &nbsp; &nbsp; get{ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return names.Where(x =&gt; x == i).FirstOrDefault(); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} }</pre><h2>Output</h2><pre class="result notranslate">A B C C</pre>
raja
Updated on 05-Nov-2020 13:40:59

Advertisements