Home > Backend Development > C#.Net Tutorial > C# array - one-dimensional array

C# array - one-dimensional array

高洛峰
Release: 2016-12-16 14:22:37
Original
1613 people have browsed it

Declare an array and assign an initial value

int[] arr = {1, 2, 3};
Copy after login

It can be seen that [] following the type name indicates an array, {} indicates a list of initial values ​​to be assigned, and each initial value is separated by a comma.

Declare an array

int[] arr = new int[3]; //正确,声明一个长度为 3 的 int 类型数组
int[3] arr2; //错误,不能这样指定数组大小
int[] arr3; //没有指定数组大小,无法使用
Copy after login

If we don’t know the value of the array in advance, we can declare the array first as described above. Of course, we should know the type and size of the array when declaring the array. The number in [] indicates that the length is not the upper bound of the subscript.

C# arrays also support dynamic specification

int len = 3;
int[] arr = new int[len];
Copy after login

Array assignment and value acquisition

int[] arr = new int[3];
arr[0] = 10; //给第一个元素赋值
int m = arr[0]; //取第一个元素的值
Copy after login

Get the array length

int[] arr = new int[3];
int len = arr.Length;
int len2 = arr.GetLength(0) //这种方法也可以获取数组长度,参数表示要获取第几维的数组长度,从 0 开始。
Copy after login

It is more convenient to apply under .NET Framework 3.5

C# 3.0 syntax is used under .NET Framework 3.5, so use Arrays are more convenient, and you can assign values ​​directly without specifying the length.

string[] colors = new string[]{"#333", "#666", "#999", "#ccc", "#fff"};
Copy after login

Declare an array colors and assign five strings to it. The length of the array here is automatically determined by the number of curly braces.



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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template