Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How is an array initialized in C#?
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. In C#, arrays must be properly initialized before you can use them to store and access data.
Array Declaration vs Initialization
Firstly, declare an array −
int[] rank;
But declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of the array. For example −
int[] rank = new int[5];
Array Initialization Methods
Using Array Literal Syntax
You can assign values to an array at the time of declaration −
using System;
class Program {
public static void Main() {
int[] rank = { 1, 2, 3, 4, 5 };
Console.WriteLine("Array elements:");
for (int i = 0; i < rank.Length; i++) {
Console.WriteLine("rank[" + i + "] = " + rank[i]);
}
}
}
The output of the above code is −
Array elements: rank[0] = 1 rank[1] = 2 rank[2] = 3 rank[3] = 4 rank[4] = 5
Using new Keyword with Size and Values
With that, you can also create and initialize an array in a single line −
using System;
class Program {
public static void Main() {
int[] rank = new int[5] { 1, 2, 3, 4, 5 };
Console.WriteLine("Array length: " + rank.Length);
Console.WriteLine("First element: " + rank[0]);
Console.WriteLine("Last element: " + rank[rank.Length - 1]);
}
}
The output of the above code is −
Array length: 5 First element: 1 Last element: 5
Using new Keyword with Inferred Size
You can also omit the size when providing initial values −
using System;
class Program {
public static void Main() {
string[] colors = new string[] { "Red", "Green", "Blue", "Yellow" };
Console.WriteLine("Color array:");
foreach (string color in colors) {
Console.WriteLine(color);
}
}
}
The output of the above code is −
Color array: Red Green Blue Yellow
Comparison of Initialization Methods
| Method | Syntax | Use Case |
|---|---|---|
| Array literal | int[] arr = {1, 2, 3}; |
When you know all values at compile time |
| New with size and values | int[] arr = new int[3] {1, 2, 3}; |
Explicit size specification |
| New with inferred size | int[] arr = new int[] {1, 2, 3}; |
When passing arrays as parameters |
| New with size only | int[] arr = new int[3]; |
When filling values later |
Conclusion
Arrays in C# can be initialized using several methods: array literal syntax for known values, the new keyword with explicit or inferred size, or declaring size only for later assignment. Choose the method that best fits your specific use case and coding style.
