Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Welcome to our blog of "Arrays in C#." Arrays play a fundamental role in C# programming, offering a powerful mechanism for efficiently storing and managing collections of data.

Array in C#

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.

What is Array in C#

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.

Important points about array 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.

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};
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

C# Array Types

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.

Multidimensional Arrays (Rectangular arrays)

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.

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

    string[] languages={"C#", "C++", "Python", "Java"};

Accessing the elements of the array in C#

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

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

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.

Now let’s learn some important points regarding array in C#.

Advantages of C# Array

  • 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. Now let’s move on to the FAQs.

Check out this array problem - Merge 2 Sorted Arrays

Frequently Asked Questions

What is an array in C#?

In C#, an array is a data structure that stores elements of the same data type in contiguous memory locations, accessible by an index.

What is ArrayList in C#?

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.

Is array a data type in C#?

No, an array is not a data type in C#. It is a data structure that holds elements of a specific data type in a sequential order.

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

Refer here to know more about loop controls in C# language.

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!

Topics covered
1.
Introduction
2.
What is Array in C#
2.1.
Important points about array in C#
2.2.
Syntax
2.3.
Examples 
3.
C# Array Types
3.1.
Single-Dimensional Arrays
3.2.
Multidimensional Arrays (Rectangular arrays)
3.3.
Jagged Arrays (Array-of-arrays)
4.
Other Ways to Create an Array in C#
4.1.
Accessing the elements of the array in C#
4.2.
C#
5.
Change an Array Element
5.1.
C#
6.
Length of the array in C#
6.1.
C#
7.
Loop through an array in C#
7.1.
C#
8.
The foreach Loop
8.1.
C#
9.
Sort Array in C#
9.1.
C#
9.2.
C#
9.3.
System.Linq Namespace
9.4.
C#
10.
Advantages of C# Array
11.
Disadvantages of C# Array
12.
Frequently Asked Questions
12.1.
What is an array in C#?
12.2.
What is ArrayList in C#?
12.3.
What is array string in C#?
12.4.
Is array a data type in C#?
13.
Conclusion