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

Interface with real life Examples

Interfaces with real life examples An interface is a programming structure/syntax that allows the computer to enforce certain properties on an object (class). For example, say we have a car class and a tricyclic class and a truck class. Each of these three classes should have a start engine() action. How the "engine is started" for each vehicle is left to each particular class, but the fact that  they must  have a start engine action is the domain of the interface. The syntax of an Interface We can implement single interface or multiple interfaces to the class. By default interfaces are public. We declare interface by using "interface" keyword. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CsharpnaijaInterfaceTutorial {     interface IEngine     {         void Start();     }...

The Out Parameter with Example in C#

  The Out Parameter with Example in C# In C#,  out  keyword is used to pass arguments to the method as a  reference type . The  out  keyword same as the  ref  keyword but the only difference is  out  doesn’t require a variable to be initialized before we pass it as an argument to the method but the  variable  must be initialized in called method before it returns a value to the calling method. The out parameter in C# is also useful to return more than one value from methods. Declaration of C# Out Parameter Following is a simple example of using  out  parameters in C#.   int x; // No need to initialize variable OutParameterMultTest ( out x ) ;   From the above declaration, we just declared a variable  x  and pass it to the method by using  out  parameter without assigning any value but as discussed, the variable must be initialized in called method before it returns a value...