C# arrays – basic information

C# arrays – basic information

An array is a place you store multiple variables of the same datatype. There are three types of arrays single-dimensional, multi-dimensional and jagged.

The single and multi arrays are what they sound like with the single dimensional array acting like a row, while the multi is like a grid, or a cube. So the single array is made like so:

type[ ] arrayName = new type[numberOfValuesBeingPutInArray];

or

type[] arrayName = {value1, Value2, Value3,etc};

You can also make a array by by doing:

type[] arrayName = newType[] {{value1, Value2, Value3,etc};

The multi-dimensional array is very similiar as it essentially just changes the [] to [ , ] or however many commas like so:

type[ , ] arrayName = new type[ numberOfRows, numberOfColumns ];

type[ , , ] arrayName = new type[ numberDimension1, numberDimension2, numberDimension3 ];

type[ , ] arrayName = {{V1,V2,etc}, {V1,V2, etc} , etc};

type[ , ] arrayName = {{{V1,V2,etc}, {V1,V2, etc} , etc}}, {{V1,V2,etc}, {V1,V2, etc} , etc} , etc} ;

You can essentially have as many dimensions as you want so long as you have the memory space for it and your compiler can handle it. If you declare an array without initializing it(assigning it values either with new or the {}, you would need to use the new operator to assign the values similar to what’s shown in the third example for single arrays.

You cannot change the length or number of dimensions after the instance of the array is made. If you don’t declare what the values in the array are they are the default for the type( 0 or null). The elements can be of any type so long as they are within the type of the array. This means that if you make the type Object (as in the object class that all types should be a part of) you can put whatever value want in it, but if you make an int array you can only put ints not anything else. When calling from an array the first value is at zero and the last value is at the number of values-1. So, arrayName[0,0] would call the value in the first column and the first row.

For example:

int array[] = {1,2,3,4,5};

System.Console.WriteLine(array[0]);

// the console will print out 1

System.Console.WriteLine(array[4]);

// the console will output 5

You can use a foreach loop to go through an array, which will be discussed in a different post. Along with some common and useful methods used with arrays.

A jagged array is an array of arrays , and this is the link to the more detailed post on them.

The Microsoft tutorial for this is here.

One thought on “C# arrays – basic information

Comments are closed.