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 declared in C#?
To declare an array in C#, you specify the data type followed by square brackets and the array name. Arrays in C# are reference types that store multiple elements of the same data type in a contiguous memory location.
Syntax
Following is the basic syntax for declaring an array −
datatype[] arrayName;
To declare and initialize an array with a specific size −
datatype[] arrayName = new datatype[size];
To declare and initialize an array with values −
datatype[] arrayName = {value1, value2, value3, ...};
Here −
-
datatype specifies the type of elements the array will store (int, double, string, etc.).
-
[] indicates that this is an array declaration.
-
arrayName is the identifier for the array.
-
size specifies the number of elements the array can hold.
Using Array Declaration and Initialization
Example
using System;
namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
int[] n = new int[10]; /* n is an array of 10 integers */
int i, j;
/* initialize elements of array n */
for (i = 0; i < 10; i++) {
n[i] = i + 100;
}
/* output each array element's value */
for (j = 0; j < 10; j++) {
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
}
}
}
The output of the above code is −
Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109
Using Array Literal Initialization
Example
using System;
class Program {
static void Main() {
// Array with initial values
string[] fruits = {"Apple", "Banana", "Orange", "Mango"};
// Another way to initialize
double[] prices = new double[] {1.5, 2.0, 1.8, 2.5};
Console.WriteLine("Fruits and their prices:");
for (int i = 0; i < fruits.Length; i++) {
Console.WriteLine("{0}: ${1}", fruits[i], prices[i]);
}
}
}
The output of the above code is −
Fruits and their prices: Apple: $1.5 Banana: $2 Orange: $1.8 Mango: $2.5
Different Array Declaration Methods
| Declaration Method | Example | Description |
|---|---|---|
| Declaration only | int[] numbers; |
Declares array variable but doesn't allocate memory |
| Declaration with size | int[] numbers = new int[5]; |
Creates array with specified size, default values |
| Declaration with values | int[] numbers = {1, 2, 3, 4, 5}; |
Creates and initializes array with given values |
| Explicit initialization | int[] numbers = new int[] {1, 2, 3}; |
Explicitly specifies array creation with values |
Conclusion
Arrays in C# are declared using the syntax datatype[] arrayName and can be initialized in multiple ways. You can declare an empty array with a specific size using new datatype[size] or initialize it directly with values using array literals for immediate use.
