Arrays in C# .NET
What is an Array?
An
array is a group of like-typed variables that are referred to by a common name. Also an array is used to store a collection or series
of elements. Each data item is called an element of the array. These elements will be of the same type.
So for example, if you had an array of Integer values, the array
could be a collection of values such as [1, 2, 3, 4, 5]. Here the number of
elements in the array is 5.
Arrays are useful when you want to store a collection of values
of the same type. So instead of declaring a variable for every element, you can
just declare one variable.
The
data types of the elements may be any valid data type like char, int, float,
etc. and the elements are stored in a contiguous location. Length of the array specifies the number of
elements present in the array. In C# the allocation of memory
for the arrays is done dynamically. And arrays are kind of objects, therefore
it is easy to find their size using the predefined functions. The variables in
the array are ordered and each has an index beginning from 0. Arrays in C# work
differently than they do in C/C++.
Important Points to Remember About Arrays in C#
·
In
C#, all arrays are dynamically allocated.
·
Since
arrays are objects in C#, we can find their length using member length. This is
different from C/C++ where we find length using sizeof operator.
·
A
C# array variable can also be declared like other variables with [] after the
data type.
·
The
variables in the array are ordered and each has an index beginning from 0.
·
C#
array is an object of base type System.Array.
·
Default
values of numeric array and reference type elements are set to be respectively
zero and null.
·
A
jagged array elements are reference types and are initialized to null.
·
Array
elements can be of any type, including an array type.
·
Array
types are reference types which are derived from the abstract base type Array.
These types implement IEnumerable and
for it, they use foreach iteration on all arrays in C#.
Array
Declaration
Syntax
:
<Data Type> [] <Array_Name>
Data
Type here defines the element type of the array.
[ ] defines the size of the array.
Array_Name here defines the Name of array.
[ ] defines the size of the array.
Array_Name here defines the Name of array.
Examples
int[] integers;// stores int values
string[] strings;//stores string values
double[] doubles;//stores double values
User[] users;//stores instances of User
Declaration
of an array alone doesn’t allocate memory to the array. For that array must be
initialized.
Array
Initialization
As
said earlier, an array is a reference type so the new keyword is used to create an instance of the
array. We can assign initialize individual array elements, with the help of the
index.
Syntax
:
Data type[] <Array_Name> = new <datatype>[size];
Data
type specifies the type of data being allocated, size specifies the number of
elements in the array, and Array_Name is the name of array variable. And new will allocate memory to an array according to
its size.
Example
//Defining
Array with size of 5 but not assign values
int[] integers = new int[5];
//Array
with assign values of size 5
int[] intAssign = new int[5] { 1,
2, 3, 4, 5 };
//Defining
array with 5 elements which indicates the size of the array
int[] intElements = { 1, 2, 3, 4, 5 };
Accessing Array Elements
At
the time of initialization, we can assign the value. But, we can also assign
the value of the array using its index randomly after the declaration and
initialization. We can access an array value through indexing, placed index of
the element within square brackets with the array name
Example
Example
////Defining
Array with size of 5 but not assign values
int[] integers = new int[5];
integers[0]
= 10;
integers[1]
= 9;
integers[2]
= 8;
var value = integers[2];
var value1 = integers[1];
var sum = value + value1;
int[] nums = { 10, 15, 16, 8, 6 };
for (int i = 0; i < nums.Length; i++)
Console.WriteLine(nums[i]); // get values of array elements
for (int i = 0; i < nums.Length; i++)
nums[i] = nums[i] + 10; // increase the value of each element by 10
Accessing Arrays using for loop
Use the for loop to get or set the values of an array elements. Use the length property of an array in conditional expression of the for loop as shown in example belowint[] nums = { 10, 15, 16, 8, 6 };
for (int i = 0; i < nums.Length; i++)
Console.WriteLine(nums[i]); // get values of array elements
for (int i = 0; i < nums.Length; i++)
nums[i] = nums[i] + 10; // increase the value of each element by 10
Access Array using foreach Loop
Use
foreach
loop to read values of an array elements without using index. This is illustrated below
int[] nums = { 10, 15, 16, 8, 6 };
foreach (var item in nums)
Console.WriteLine(item);
string[] names = { "Musa", "Sule", "Gadabs", "Sakinat" };
foreach (var name in names)
Console.WriteLine(name);
One Dimensional Array
This array contains only one row for
storing the values. All values of this array are stored contiguously starting
from 0 to the array size. For example, declaring a single-dimensional array of
5 integers
int[] integers = new int[5];
The above array contains the
elements from integers[0] to integers[4].
From the above, the new operator has to create the array and also initialize
its element by their default values. Above example, all elements are initialized
by zero, because it is of int type.
Example
private void
ArrayTest()
{
// declares a
1D Array of string.
string[] monthsOftheYear;
// allocating
memory for days.
monthsOftheYear = new string[] {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul","Aug","Sep","Oct","Nov","Dec"};
// Displaying
Elements of array
foreach (string mon in monthsOftheYear)
{
Console.Write(mon + " ");
}
}
Multidimensional Arrays
The
multi-dimensional array contains more than one row to store the values. It is
also known as a Rectangular Array in C# because it’s each row length is same. It can be
a 2D-array or 3D-array or
more. To storing and accessing the values of the array, one required the nested
loop. The multi-dimensional array declaration, initialization and accessing is
as follows;
//
creates a two-dimensional array of
// four
rows and two columns.
int[,] multi2DimIntArray = new int[4, 2];
//creates
an array of three dimensions, 4, 2, and 3
int[,,] multi3DimIntArray = new int[4, 2, 3];
Jagged Arrays
An
array whose elements are arrays is known as Jagged arrays it means “array of arrays“. The jagged array elements may be of
different dimensions and sizes. Below are the examples to show how to declare,
initialize, and access the jagged arrays.
Example
//
Declare the array of two elements:
int[][] jaggedArr = new int[2][];
//
Initialize the elements:
jaggedArr[0]
= new int[5] { 1, 3, 5, 7, 9 };
jaggedArr[1] = new int[4] { 2, 4, 6,
8 };
It’s
possible to mix jagged and multidimensional arrays. The jagged array is an
array of arrays, and therefore its elements are reference types and are
initialized to null.
Note:
·
GetLength(int):
returns the number of elements in the first dimension of the Array.
·
When
using jagged arrays be safe, if the index does not exist then it will throw
exception which is IndexOutOfRange.
Comments
Post a Comment