An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. 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.
The array has can contain primitive data types as well as objects of a class depending on the definition of an array. Whenever use primitives data types, the actual values have to be stored in contiguous memory locations. In the case of objects of a class, the actual objects are stored in the heap segment.
The following figure shows how array stores values sequentially:

Explanation: The index is starting from 0, which stores value. we can also store a fixed number of values in an array. Array index is to be increased by 1 in sequence whenever its not reach the array size.
Array Declaration
Syntax:
<Data Type>[ ] <Name_Array>
Here,
- <Data Type> : It define the element type of the array.
- [ ] : It define the size of the array.
- <Name_Array> : It is the Name of array.
Note : Only Declaration of an array 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 used to create an instance of the array. We can assign initialize individual array elements, with the help of the index.
Syntax:
type [ ] < Name_Array > = new < datatype > [size];
Here, type specifies the type of data being allocated, size specifies the number of elements in the array, and Name_Array is the name of an array variable. And new will allocate memory to an array according to its size.
Examples: To Show Different ways for the Array Declaration and Initialization
Syntax
| Use Cases
| Example
|
|---|
<data_type>[] <arr_name> = new <data_type>[size];
| Defining array with size, but not assigns values
| int[] arr1 = new int[5];
|
<data_type>[] <arr_name> = new <data_type>[size]{ array_elements};
| Defining array with size and assigning the values at the same time
| int[] arr2 = new int[5]{1, 2, 3, 4, 5};
|
<data_type>[] <arr_name> = { array_elements};
| The value of the array is directly initialized without taking its size
| int[] intArray3 = {1, 2, 3, 4, 5};
|
Initialization of an Array after Declaration
Arrays can be initialized after the declaration. It is not necessary to declare and initialize at the same time using the new keyword. However, Initializing an Array after the declaration, it must be initialized with the new keyword. It can’t be initialized by only assigning values.
Example:
// Declaration of the array
string[] str1, str2;
// Initialization of array
str1 = new string[5]{ “Element 1”, “Element 2”, “Element 3”, “Element 4”, “Element 5” };
str2 = new string[5]{ “Element 1”, “Element 2”, “Element 3”, “Element 4”, “Element 5” };
Note : Initialization without giving size is not valid in C#. It will give a compile-time error.
Example: Wrong Declaration for initializing an array
// Compile-time error: must give size of an array
int[] intArray = new int[];
// Error : wrong initialization of an array
string[] str1;
str1 = {“Element 1”, “Element 2”, “Element 3”, “Element 4” };
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: Accessing Array elements using different loops
C#
// Accessing array elements using different loops
using System;
class Geeks
{
// Main Method
public static void Main()
{
// declares an Array of integers.
int[] intArray;
// allocating memory for 5 integers.
intArray = new int[5];
// initialize the first elements
// of the array
intArray[0] = 10;
// initialize the second elements
// of the array
intArray[1] = 20;
// so on...
intArray[2] = 30;
intArray[3] = 40;
intArray[4] = 50;
// accessing the elements
// using for loop
Console.Write("For loop :");
for (int i = 0; i < intArray.Length; i++)
Console.Write(" " + intArray[i]);
Console.WriteLine("");
Console.Write("For-each loop :");
// using for-each loop
foreach(int i in intArray)
Console.Write(" " + i);
Console.WriteLine("");
Console.Write("while loop :");
// using while loop
int j = 0;
while (j < intArray.Length) {
Console.Write(" " + intArray[j]);
j++;
}
Console.WriteLine("");
Console.Write("Do-while loop :");
// using do-while loop
int k = 0;
do
{
Console.Write(" " + intArray[k]);
k++;
} while (k < intArray.Length);
}
}
OutputFor loop : 10 20 30 40 50
For-each loop : 10 20 30 40 50
while loop : 10 20 30 40 50
Do-while loop : 10 20 30 40 50
Types of Arrays in C#
There are three types of Arrays C# supports as mentioned below:
- One Dimensional Array
- Multi Dimensional Array
- Jagged Array
1. One Dimensional Array
In 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[] arrayint = new int[5];
The above array contains the elements from arrayint[0] to arrayint[4]. Here, 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 the int type.
Example:
C#
// Demonstration of One-Dimensional Array
using System;
class Geeks
{
// Main Method
public static void Main()
{
// declares a 1D Array of string.
string[] weekDays;
// allocating memory for days.
weekDays = new string[] { "Sun", "Mon", "Tue", "Wed",
"Thu", "Fri", "Sat" };
// Displaying Elements of array
foreach(string day in weekDays)
Console.Write(day + " ");
}
}
OutputSun Mon Tue Wed Thu Fri Sat
2. 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[, ] intarray = new int[4, 2];
//creates an array of three dimensions, 4, 2, and 3
int[,, ] intarray1 = new int[4, 2, 3];
Example:
C#
// Demonstration of multi- dimensional array
using System;
class Geeks
{
// Main Method
public static void Main()
{
// The same array with dimensions
// specified 2, 2 and 3.
int[,, ] arr = new int[2, 2, 3] { { { 1, 2, 3 },
{ 4, 5, 6 } },
{ { 7, 8, 9 },
{ 10, 11, 12 } } };
// Checking elements at particular index
Console.WriteLine("arr[1][0][1] : "
+ arr[1, 0, 1]);
Console.WriteLine("arr[1][1][2] : "
+ arr[1, 1, 2]);
}
}
Outputarr[1][0][1] : 8
arr[1][1][2] : 12
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: Showing how to declare, initialize, and access the jagged arrays
C#
// Demonstration of Jagged Array
using System;
class Geeks
{
// Main Method
public static void Main()
{
// Declaring Jagged Array
int[][] arr = { new int[] { 1, 3, 5, 7, 9 },
new int[] { 2, 4, 6, 8 } };
Console.WriteLine("Arrays :");
// Display the array elements:
for (int i = 0; i < arr.Length; i++)
{
System.Console.Write("Elements[" + i + "] Array: ");
// Printing the elements of array
for (int j = 0; j < arr[i].Length; j++) {
Console.Write(arr[i][j] + " ");
}
Console.WriteLine();
}
}
}
OutputArrays :
Elements[0] Array: 1 3 5 7 9
Elements[1] Array: 2 4 6 8
Points To Remember:
- GetLength(int): returns the number of elements in the first dimension of the Array.
- When using jagged arrays be safe as if the index does not exist then it will throw exception which is IndexOutOfRange.
Important Points to Remember About Arrays
- 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#.
Similar Reads
Introduction
C# Tutorial
C# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET Framework
The .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The framework includes a variety of programming languages, such as C#, F#, and Visual
7 min read
C# | .NET Framework (Basic Architecture and Component Stack)
Microsoft created the language C#, known as C Sharp, in the year 2000. C# is an object-oriented programming language that is used in .NET Framework. C# is designed to be simple, efficient, and versatile, and is often used to build a wide range of desktop, web, and mobile applications. The .NET Frame
6 min read
Hello World in C#
The Hello World! program is the most basic and first program when you dive into a new programming language. This simply prints the Hello World! on the output screen. In C#, a basic program consists of the following: A Namespace DeclarationClass Declaration & DefinitionClass Members(like variable
3 min read
Common Language Runtime (CLR) in C#
The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others. When a C# program is compiled, t
6 min read
Fundamentals
C# Identifiers
In programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. Example: public class GFG { static public void Main () { int
2 min read
C# Data Types
Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# Variables
In C#, variables are containers used to store data values during program execution. So basically, a Variable is a placeholder of the information which can be changed at runtime. And variables allows to Retrieve and Manipulate the stored information. In Brief Defination: When a user enters a new valu
4 min read
C# | Literals
The fixed values are called as Literal. Literal is a value that is used by the variables. Values can be either an integer, float or string, etc. // Here 100 is a constant/literal.int x = 100; Literals can be of the following types: Integer LiteralsFloating-point LiteralsCharacter LiteralsString Lite
5 min read
C# Operators
In C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result. Types of Opera
8 min read
C# | Keywords
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. Example: // C# Program to illustrate the key
7 min read
Control Statements
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)
Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These
5 min read
C# Switch Statement
In C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.
4 min read
C# Loops
Looping in a programming language is a way to execute a statement or a set of statements multiple times depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops. Loops are mainly divided into two categories
5 min read
C# Jump Statements (Break, Continue, Goto, Return and Throw)
In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#. Types of Jump StatementsThere are mainly five keywords in t
4 min read
Arrays
C# Arrays
An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. 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 spe
8 min read
C# Jagged Arrays
A jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows
5 min read
C# | Array Class
The Array class gives methods for creating, manipulating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base class for language implementati
7 min read
How to sort an Array in C# | Array.Sort() Method Set - 1
Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows: Sort<T>(T[]) Method Sort<T>(T[], IComparer<T>) Method Sort<T>(T[], Int32, Int32) Method Sort<T>(T[], Comparison<T>) Method S
7 min read
How to find the rank of an array in C#
Array.Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Syntax: public int Rank { get; } Property Value: It returns the rank (number of dimensions) of the Array of type System.Int32. B
2 min read
Collections & Generics
Collections in C#
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-c
5 min read
C# | Collection Class
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-chil
5 min read
C# | Generics - Introduction
Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfac
6 min read
List Implementation in C#
In C#, List is a generic collection which is used to store the elements or objects in the form of a list and it is defined under System.Collection.Generic namespace. It provides the same functionality like ArrayList, but there is only one difference i.e., a list is a generic whereas ArrayList is a n
7 min read
C# SortedList with Examples
In C#, SortedList is a collection of key/value pairs which are sorted according to keys. By default, this collection sort the key/value pairs in ascending order. It is of both generic and non-generic type of collection. The generic SortedList is defined in System.Collections.Generic namespace wherea
6 min read
HashSet in C# with Examples
In C#, HashSet is an unordered collection of unique elements. This collection is introduced in .NET 3.5. It supports the implementation of sets and uses the hash table for storage. This collection is of the generic type collection and it is defined under System.Collections.Generic namespace. It is g
6 min read
SortedSet in C# with Examples
In C#, SortedSet is a collection of objects in sorted order. It is of the generic type collection and defined under System.Collections.Generic namespace. It also provides many mathematical set operations, such as intersection, union, and difference. It is a dynamic collection means the size of the S
4 min read
C# Dictionary with examples
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collections.Generic namespace. It is dynamic in
5 min read
SortedDictionary Implementation in C#
In C#, SortedDictionary is a generic collection that is used to store the key/value pairs in the sorted form and the sorting is done on the key. SortedDictionary is defined under System.Collection.Generic namespace. It is dynamic in nature means the size of the sorted dictionary is growing according
8 min read
C# Hashtable with Examples
A Hashtable is a collection of key/value pairs that are arranged based on the hash code of the key. In other words, a Hashtable is used to create a collection that uses a hash table for storage. It generally optimizes the lookup by calculating the hash code of every key and storing it into another b
6 min read
C# Stack with Examples
A Stack represents a last-in, first-out collection of objects. It is used when you need last-in, first-out access to items. It is both a generic and non-generic type of collection. The generic stack is defined in System.Collections.Generic namespace whereas non-generic stack is defined under System.
6 min read
C# Queue with Examples
A Queue is used to represent a first-in, first out(FIFO) collection of objects. It is used when you need first-in, first-out access of items. It is the non-generic type of collection which is defined in System.Collections namespace. It is used to create a dynamic collection which grows, according to
6 min read
Linked List Implementation in C#
A LinkedList is a linear data structure which stores element in the non-contiguous location. The elements in a linked list are linked with each other using pointers. Or in other words, LinkedList consists of nodes where each node contains a data field and a reference(link) to the next node in the li
6 min read
ASP.NET Interview Questions and Answer
ASP.NET is a popular framework by Microsoft for building fast and scalable web applications. It allows developers to create dynamic websites, services, and apps, using server-side code and offering a user-friendly experience. Trusted by companies like Microsoft, Dell, and Accenture, ASP.NET is used
15+ min read