Page 190 - CSharp/C#
P. 190

["foo"] = 34,
             ["bar"] = 42
         };


        Any object that has an indexed getter or setter can be used with this syntax:


         class Program
         {
             public class MyClassWithIndexer
             {
                 public int this[string index]
                 {
                     set
                     {
                         Console.WriteLine($"Index: {index}, value: {value}");
                     }
                 }
             }

             public static void Main()
             {
                 var x = new MyClassWithIndexer()
                 {
                     ["foo"] = 34,
                     ["bar"] = 42
                 };

                 Console.ReadKey();
             }
         }


        Output:


              Index: foo, value: 34
              Index: bar, value: 42

        View Demo

        If the class has multiple indexers it is possible to assign them all in a single group of statements:


         class Program
         {
             public class MyClassWithIndexer
             {
                 public int this[string index]
                 {
                     set
                     {
                         Console.WriteLine($"Index: {index}, value: {value}");
                     }
                 }
                 public string this[int index]
                 {
                     set
                     {
                         Console.WriteLine($"Index: {index}, value: {value}");
                     }




        https://riptutorial.com/                                                                             136
   185   186   187   188   189   190   191   192   193   194   195