Home >Backend Development >C#.Net Tutorial >Detailed explanation of C# one-dimensional array initialization

Detailed explanation of C# one-dimensional array initialization

高洛峰
高洛峰Original
2016-12-16 14:45:102939browse

Before understanding C# one-dimensional array, let’s take a look at what is an array? An array is a collection of variables of the same type, which can be referenced by the same name. Arrays are composed of continuous storage units. The lowest address corresponds to the first element of the array, and the highest address corresponds to the last element. The array can be one-dimensional or multi-dimensional.

C# The concept of one-dimensional array

A one-dimensional array is essentially a one-dimensional array composed of similar data

You can declare an array composed of 5 integers as shown in the following example:

int[] array = new int[5];

This array contains elements from array[0] to array[4]. The new operator is used to create an array and initialize the array elements to their default values. In this example, all array elements are initialized to zero.

Arrays storing string elements can be declared in the same way. For example:

string[] stringArray = new string[6];

C# Initialization of one-dimensional array

You can initialize the array when declaring it, in which case no level specifier is needed because the level specifier is already provided by the number of elements in the initialization list. For example:

int[] array1 = new int[5] { 1, 3, 5, 7, 9 };

can initialize a string array in the same way. The following declares an array of strings where each array element is initialized with the name of each day:

string[] weekDays =   
new string[] { "Sun", "Mon", "Tue",   
"Wed", "Thu", "Fri", "Sat" };

If you initialize the array when declaring it, you can use the following shortcut:

int[] array2 = { 1, 3, 5, 7, 9 };  
string[] weekDays2 = { "Sun", "Mon",  
 "Tue", "Wed", "Thu", "Fri", "Sat" };

You can declare an array variable but not initialize it , but you must use the new operator when assigning an array to this variable. For example:

int[] array3;  
array3 = new int[] { 1, 3, 5, 7, 9 };   // OK  
//array3 = {1, 3, 5, 7, 9};   // Error

The concepts and content related to the initialization of C# one-dimensional arrays are introduced to you here. I hope it will be helpful for you to understand and learn the initialization of C# one-dimensional arrays.



For more detailed explanations of C# one-dimensional array initialization and related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn