In C#, an Array is a data structure that holds a fixed number of elements of a single type. The elements are stored sequentially and can be accessed by their index. The size of an array is determined at the time of declaration and cannot be changed later.
The array's length specifies the number of elements in the array in C#. The memory allocation for arrays in C# is done dynamically. Since in C# arrays are objects, it is simple to determine their size using the built-in functions.
Instead of defining distinct variables for each item, arrays in C# hold multiple values in a single variable.
Important Points to Remember About Arrays in C#
All arrays in C# are allocated dynamically.
Because arrays are objects in C#, we can use member length to determine their length. This differs from C/C++, where the sizeof operator is used to determine the length.
With [] following the data type, a C# array variable can be declared just like any other variable.
The array's variables are sorted, and each has an index starting at 0.
Array in C# is an object of base type System.
The default values for numeric array and reference type elements are zero and null, respectively.
The elements of a jagged array are reference types that are initialized to null.
The elements of an array can be of any type, including array types.
C# Array Declaration
Syntax
Syntax: The following is the syntax of declaration of an array in C#
< Data Type > [ ] < name_of_the_array >
Examples
The following are some example to declare array in C# of various data types.
int[] x; // it is used to store int values
string[] s; // it is used to store string values
double[] d; // it is used to store double values
Student[] stud1; // it is used to store instances of Student class which is a custom class
In the above example, Square brackets are used to declare the array to define the variable type.
string[ ] languages;
The above shows that languages stores an array of strings.
An array literal can be used to assign multiple values to it by placing the items in a comma-separated list inside curly braces:
string[ ] languages = {"C#", "C++", "Python", "Java"};
To create an integer array in C#, we could write:
int[ ] myNum = {1, 12, 3, 5, 6};
C# Array Types
There are 3 types of arrays in C# programming:
Single Dimensional Array
Multidimensional Array
Jagged Array
Lets learn about them in detail
1. C# Single-Dimensional Arrays
These are the simplest type of array that store a sequence of items of the same type. Here's an example:
int[] array1 = new int[5] {1, 2, 3, 4, 5}; // This creates an array of integers of length 5.
These are arrays with more than one dimension. For example, a 2D array can be thought of as a table with rows and columns
int[,] array2 = new int[3, 2] {{1, 2}, {3, 4}, {5, 6}}; // This creates a 2D array with 3 rows and 2 columns.
3. C# Jagged Arrays (Array-of-arrays)
These are arrays whose elements are arrays themselves. These elements can be of different dimensions and sizes, unlike Multidimensional arrays.
int[][] array3 = new int[2][]; // This creates a jagged array with two elements,where the first element is an array of 3 integers and the second element is an array of 4 integers.
array3[0] = new int[3] {1, 2, 3};
array3[1] = new int[4] {4, 5, 6, 7};
Other Ways to Create an Array in C#
// Creates an array of four elements, and add values later
string[] languages = new string[4];
// It creates an array of four elements and add values right away
string[] languages= new string[4] {"C#", "C++", "Python", "Java"};
// It creates an array of four elements without specifying the size
string[] languages= new string[] {"C#", "C++", "Python", "Java"};
// It creates an array of four elements, omitting the new keyword, and without specifying the size
You can access an array element by referring to the index number. The following statement accesses the value of the first element in the array languages:
C#
C#
using System; class Practice { static void Main() { string[] languages = {"C#", "C++", "Python", "Java"}; Console.WriteLine(languages[0]); } }
Output
C#
Change an Array Element in C#
To change the value of a specific element in an array, access the element by referring to the index number and change its value.
C#
C#
using System; class Practice { static void Main() { string[] languages = {"C#", "C++", "Python", "Java"}; languages[1] = "C"; Console.WriteLine(languages[1]); // Now outputs C instead of C++ } }
Output
C
Length of the array in C#
For calculating the length of the array in C#, we use .Length method. The following example shows how to find the length of an array.
C#
C#
using System; class Practice { static void Main() { string[] languages = {"C#", "C++", "Python", "Java"}; Console.WriteLine(languages.Length); } }
Output
4
Loop through an array in C#
The for loop can be used to loop through the array elements, and the Length property can be used to determine how many times the loop should execute. In the following example, all the array elements will be printed.
C#
C#
using System; class Practice { static void Main() { string[] languages = {"C#", "C++", "Python", "Java"}; for (int i = 0; i < languages.Length; i++) { Console.WriteLine(languages[i]); } } }
Output
C#
C++
Python
Java
The foreach Loop in C#
The foreach loop is exclusively used to loop through the elements in an array.
C#
C#
using System; class Practice { static void Main() { string[] languages = {"C#", "C++", "Python", "Java"}; foreach (string i in languages) { Console.WriteLine(i); } } }
Output
C#
C++
Python
Java
Sort Array in C#
The sort method sorts an array alphabetically or in ascending order. Let's see an example to understand sort in C#.
C#
C#
using System; class Practice { static void Main() { // Sort an array of string string[] languages = {"C#", "C++", "Python", "Java"}; Array.Sort(languages); foreach (string i in languages) { Console.WriteLine(i); } } }
Output
C#
C++
Java
Python
Let's see an example to sort an array of integers.
C#
C#
using System; class Practice { static void Main() { // Sort an array of int int[] myNums = {1, 9, 8, 5, 4, 2}; Array.Sort(myNums); foreach (int i in myNums) { Console.WriteLine(i); } } }
Output
1
2
4
5
8
9
System.Linq Namespace
Other useful array methods, such as Min, Max, and Sum, can be found in the System.Linq namespace:
C#
C#
using System; using System.Linq;
namespace MyApplication { class Program { static void Main(string[] args) { int[] myNums = {5, 1, 8, 9, 3, 4, 5}; Console.WriteLine(myNums.Max()); // returns the largest value Console.WriteLine(myNums.Min()); // returns the smallest value Console.WriteLine(myNums.Sum()); // returns the sum of elements } } }
Output
9
1
35
Where 9 is the max element in the myNums array, 1 is the minimum, and the sum of the array is 35.
Advantages of C# Arrays
Type-Safety: Arrays in C# are type-safe. This means they hold a specific type of values, reducing runtime type errors.
Indexing: Each element in the array has a unique index, making it easy to access and modify elements.
Efficient Memory Use: Arrays store data in contiguous memory locations, improving space and retrieval efficiency.
Multidimensional: C# supports multidimensional and jagged arrays, making it possible to create complex, structured data arrangements.
Built-in Methods: Arrays in C# have built-in methods for sorting, searching, etc., increasing code readability and efficiency.
Iteration: Iterating over an array using loops or other iteration statements is straightforward, simplifying data processing.
Compatibility with LINQ: Arrays in C# are compatible with Language Integrated Query (LINQ), allowing for powerful data querying capabilities.
Disadvantages of C# Array
Fixed Size: Once an array is declared, its size cannot be modified without creating a completely new array.
Complexity: Operations like insertion and deletion are complex in arrays, as they require shifting elements.
Memory Wastage: If not all elements of an array are used, memory can be wasted.
No Direct Method for Array Resizing: To resize an array, one has to create a new array and copy elements from the old array, which can be inefficient.
Lack of Higher-level Operations: Compared to other data structures like Lists or HashSets, arrays do not provide built-in higher-level operations such as RemoveAt, InsertAt, etc.
Performance: In some cases, like adding elements in the middle of an array, performance can be slow due to the necessity of shifting elements.
An ArrayList in C# is a dynamic array-like collection that can store elements of different data types and automatically adjusts its size.
What is array string in C#?
An array of strings in C# is a collection of string elements arranged in a specific order, allowing for efficient storage and retrieval of text data.
How to display an array in C#?
To display an array in C#, use a loop (e.g., for or foreach) to iterate through the array elements and print each element using Console.WriteLine().
What is array size in C#?
In C#, the size of an array is determined at initialization and cannot be changed. Use the Length property to get the number of elements in the array.
Conclusion
This article extensively discussed the array in C# language and how we can use it in our program. We learned the syntax of array declaration, accessing elements of the array, sorting the array, and its implementation with multiple examples. We learned multiple ways to create an array in C# and some important points about arrays in C#.
We hope that this blog has helped you enhance your knowledge regarding arrays in C#, and if you would like to learn more, check out our articles in the code studio library. Do upvote our blog to help other ninjas grow. Happy Coding!