Page 103 - CSharp/C#
P. 103

Array covariance


         string[] strings = new[] {"foo", "bar"};
         object[] objects = strings; // implicit conversion from string[] to object[]


        This conversion is not type-safe. The following code will raise a runtime exception:


         string[] strings = new[] {"Foo"};
         object[] objects = strings;

         objects[0] = new object(); // runtime exception, object is not string
         string str = strings[0];   // would have been bad if above assignment had succeeded


        Getting and setting array values



         int[] arr = new int[] { 0, 10, 20, 30};

         // Get
         Console.WriteLine(arr[2]); // 20

         // Set
         arr[2] = 100;

         // Get the updated value
         Console.WriteLine(arr[2]); // 100


        Declaring an array


        An array can be declared and filled with the default value using square bracket ([]) initialization
        syntax. For example, creating an array of 10 integers:



         int[] arr = new int[10];

        Indices in C# are zero-based. The indices of the array above will be 0-9. For example:



         int[] arr = new int[3] {7,9,4};
         Console.WriteLine(arr[0]); //outputs 7
         Console.WriteLine(arr[1]); //outputs 9


        Which means the system starts counting the element index from 0. Moreover, accesses to
        elements of arrays are done in constant time. That means accessing to the first element of the
        array has the same cost (in time) of accessing the second element, the third element and so on.


        You may also declare a bare reference to an array without instantiating an array.


         int[] arr = null;   // OK, declares a null reference to an array.
         int first = arr[0]; // Throws System.NullReferenceException because there is no actual array.

        An array can also be created and initialized with custom values using collection initialization
        syntax:



        https://riptutorial.com/                                                                               49
   98   99   100   101   102   103   104   105   106   107   108