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

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...