Syntax of Accessing Array Elements in C#
This topic contains and tries to cover following subjects
- Brief information of array index mechanism
- Syntax of accessing array elements using its indexers
- Brief explanation of how Indexing works in C# arrays
- Changing an item value of an array in basic
Articles tries to provide answer to following questions and issues:
- How to access an element of one dimensional C# array?
Syntax of Accessing Array Elements in C#
In C#, array elements are accessed by their Index numbers. Array indexes start with value zero. Therefore, The last item in an array is accessed by arraysize-1. When 4 item is desired to be stored in a C# array, size is required to be provided as 3. Index values are integer.
-Array Name- [index Value]
Syntax example of Accessing Array Elements in C#
Following example shows Syntax of Accessing Array Elements. In example, a simple one dimensional array is created. It stores string type 3 elements. We access to the 2nd element in array to demonstrate, and change its value.
//create a simple array and add some elements into it...///
string [] v_arr_places = new string [] {"nebraska","nevada","brooklyn"};
//Accessing 2nd element of our Array (its value is nevada at the moment). We change
it to California...///
//index 0 item is nebraska...///
//index 1 item is nevada...///
//index 2 item is brooklyn...///
v_arr_places[1]="california";
In our array example, 2nd item in the array is changed. Notice that Index starts with zero. Nevada was 2nd item, and we accessed that element with indicating index value 1 (Not 2). More practically to say, C# Arrays count its items starting from zero.