Home >Backend Development >C#.Net Tutorial >A brief analysis of defining integer arrays in C#

A brief analysis of defining integer arrays in C#

高洛峰
高洛峰Original
2016-12-16 14:57:283093browse

 Arrays in C# are reference types. The way to define integer arrays in C# is:

 int [] intArray = {1,2,3}; or int [] intArray = new int[10];

  And in C++, integer arrays are defined The method of type array is:

 int intArray[] = {1,2,3}; or int * intArray = new int[10];

 C# defines that integer array can be one-dimensional or multi-dimensional, Matrices and ragged arrays are also supported.

Note: The way to define a multi-dimensional array (matrix) is [,,] and the way to define a multi-dimensional "staggered matrix" is [][]. In addition, the use of the new keyword does not necessarily mean that the object is dynamically allocated (entered on the stack).

 The following is a common way to define (one-dimensional) multi-dimensional arrays in C#:


 
 int []a1; //Define a one-dimensional array
 int [,]a2; //Define a two-dimensional array
 int [,, ]a3; //Define a three-dimensional array
 int []a1 = new int [10]; //Define the depth of a one-dimensional array
 int [,]a2 = new int [10,20]; //Define the depth of a two-dimensional array
int [,,]a3 = new int [10,20,30]; //Define three-digit array depth
 int []a1 = new int []{1,2,3}; //Initialization
 int [,] a2 = new int [,]{{1,2,3},{4,5,6}};

 You can also define a "ragged" array:


 
 int [][]var = new int [3][];
var[0] = new int[]{1,2,3};
var[1] = new int[]{1,2,3,4,5,6};
var[2] = new int[]{1,2,3,4,5,6,7,8,9};

 Note, the difference between int [,]a and int [][]a: the definition of the former defines a two-dimensional fixed array, which defines a two-dimensional variable array. It's just that they haven't been allocated space and initialized yet. int [][]var = new int[3][4]; is wrong.

  The following error:


 
 class Test
 {
 static void F(int []arr){}
 static void Main()
 {
 F({1,2,3});//Error! {1,2,3} is not a valid expression.
 }
 }
 
 class Test
 {
 statci void F(int []arr){}
 static void Main()
 {
 F(new int []{1,2,3});
 }
 }

 The above introduces the definition of integer array in C#


For more articles related to the definition of integer array in C#, 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