xxxxxxxxxx
int[] array1 = new int[] { 1, 2, 3 };
//or
int[] array2= { 1, 2, 3 };
// declare implicitly typed
var array3 = new int [3];
xxxxxxxxxx
int[] array = new int[]{1, 2, 3, 4, 5};
foreach (string i in array)
{
Console.WriteLine(i);
}
//or
for(int i=0; i<array.Length; i++){
Console.WriteLine(array[i]);
}
xxxxxxxxxx
int[] array = new int[]{1, 2, 3, 4, 5};
for(int i=0; i<array.Length; i++){
Console.WriteLine(array[i]);
}
xxxxxxxxxx
// Define and Initialize
int[] arr = {1, 2, 3};
// Buuuut:
// Initial defining
int[] arr;
// This works
arr = new int[] {1, 2, 3};
// This will cause an error
// arr = {1, 2, 3};
xxxxxxxxxx
// There are actually many ways to create an array in C#
// The worst method
int[] array1 = new int[3];
array1[0] = 1;
array1[1] = 2;
array1[2] = 3;
// Declare a single-dimensional array of 5 integers
int[] array1 = new int[5];
// Declare and set array element values
int[] array2 = new int[5] { 1, 2, 3, 4, 5 };
// Alternative syntax
int[] array3 = { 1, 2, 3, 4, 5 };
// Declare a two dimensional array
int[,] multiDimensionalArray1 = new int[2, 3];
// Declare and set array element values
int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };
// Declare a jagged array
int[][] jaggedArray = new int[6][];
// Set the values of the first array in the jagged array structure
jaggedArray[0] = new int[4] { 1, 2, 3, 4 };
xxxxxxxxxx
// Syntax:
datatype_variable[dimension] = new datatype[size]{array};
// For example:
string MyArray[] = new string[1]{"Hello","World"};
// or just:
string MyArray[]={"Hello","world"};
// for multidimensions:
// 2D array:
// 2 arrays, 3 values //
int MyArray=[,]=new int[1,2]{
{1,2,3},
{1,2,3}
}
// 3D array:
// 2 arrays, 3 arrays, 4 values //
int MyArray=[,,]=new int[1,2,3]{
{
{1,2,3,4},
{1,2,3,4},
{1,2,3,4}
},
{
{1,2,3,4},
{1,2,3,4},
{1,2,3,4}
}
}
xxxxxxxxxx
int[] luckyNumbers = { 4, 8, 15, 16, 23, 42};
luckyNumbers[1] = 900;
string[] friends = new string[3];
friends[0] = "Jim";
friends[1] = "Kelly";
friends[2] = "John";
friends[3] = "Ben";
Console.WriteLine(luckyNumbers[1]);
Console.ReadLine();
The first example creates an array of integers with five elements, while the second example creates an array of strings with three initial elements. The third example creates a two-dimensional array with two rows and two columns.
xxxxxxxxxx
// create an array of integers
int[] numbers = new int[5];
// create an array of strings with initial values
string[] names = new string[] {"John", "Jane", "Bob"};
// create a multidimensional array
int[,] matrix = new int[2,2];
Use the var keyword to create an array without specifying its type explicitly:
xxxxxxxxxx
// create an array of integers
var numbers = new int[] {1, 2, 3, 4, 5};
This will create an array of integers with five elements and assign it to the numbers variable.