Csharp Arrays
Csharp Arrays
http://www.tutorialspoint.com/csharp/csharp_arrays.htm
Copyright tutorialspoint.com
An array stores a fixed-size sequential collection of elements of the same type. An array is used to
store a collection of data, but it is often more useful to think of an array as a collection of variables
of the same type stored at contiguous memory locations.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99]
to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Declaring Arrays
To declare an array in C#, you can use the following syntax:
datatype[] arrayName;
where,
datatype is used to specify the type of elements in the array.
[ ] specifies the rank of the array. The rank specifies the size of the array.
arrayName specifies the name of the array.
For example,
double[] balance;
Initializing an Array
Declaring an array does not initialize the array in the memory. When the array variable is
initialized, you can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of the array.
For example,
double[] balance = new double[10];
You can assign values to the array at the time of declaration, as shown:
double[] balance = { 2340.0, 4523.69, 3421.0};
{ 99,
{ 99,
You can copy an array variable into another target array variable. In such case, both the target
and source point to the same memory location:
int [] marks = new int[]
int[] score = marks;
{ 99,
When you create an array, C# compiler implicitly initializes each array element to a default value
depending on the array type. For example, for an int array all elements are initialized to 0.
When the above code is compiled and executed, it produces the following result:
Element[0]
Element[1]
Element[2]
Element[3]
Element[4]
Element[5]
Element[6]
Element[7]
Element[8]
Element[9]
=
=
=
=
=
=
=
=
=
=
100
101
102
103
104
105
106
107
108
109
When the above code is compiled and executed, it produces the following result:
Element[0]
Element[1]
Element[2]
Element[3]
Element[4]
Element[5]
Element[6]
Element[7]
Element[8]
Element[9]
=
=
=
=
=
=
=
=
=
=
100
101
102
103
104
105
106
107
108
109
C# Arrays
There are following few important concepts related to array which should be clear to a C#
programmer:
Concept
Description
Multi-dimensional arrays
Jagged arrays
Param arrays
Param arrays
function.