Skip to main content

Arrays in C# .NET


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.
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
////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;

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 below

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

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

Popular posts from this blog

Collections in C#

Collections in C# In our previous article , we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name. What is Collections in C#? Collections are similar to Arrays, it provides a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#. There are three distinct collection types in C#: standard generic concurrent The standard collections are found under the System.Collections. They do not store elemen...

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

System.IO Namesapce in C#

  System.IO Namesapce in C# A  file  is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a  stream . The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the  input stream  and the  output stream . The  input stream  is used for reading data from file (read operation) and the  output stream  is used for writing into the file (write operation). From the above definition of file, the C# provides a namespace that enable us to manipulate file in C# called System.IO.   System.IO  is a  namespace  and it contains a standard IO (input/output) types such as classes , structures , enumerations , and  delegates  to perform a read/write operations on different sources like file, memory, network, etc.   System.IO Classes The table below shows differen...