Page 191 - CSharp/C#
P. 191

}
             }

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


        Output:


              Index: foo, value: 34
              Index: bar, value: 42
              Index: 10, value: Ten
              Index: 42, value: Meaning of life

        It should be noted that the indexer set accessor might behave differently compared to an Add
        method (used in collection initializers).

        For example:


         var d = new Dictionary<string, int>
         {
             ["foo"] = 34,
             ["foo"] = 42,
         }; // does not throw, second value overwrites the first one


        versus:


         var d = new Dictionary<string, int>
         {
             { "foo", 34 },
             { "foo", 42 },
         }; // run-time ArgumentException: An item with the same key has already been added.



        String interpolation


        String interpolation allows the developer to combine variables and text to form a string.




        Basic Example




        Two int variables are created: foo and bar.


         int foo = 34;



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