How to Create Array in C#: Syntax and Examples
In C#, you create an array using the
type[] arrayName = new type[size]; syntax, where type is the data type and size is the number of elements. You can also initialize an array with values using type[] arrayName = {value1, value2, ...};.Syntax
To create an array in C#, use the following syntax:
- type[] arrayName; declares an array variable.
- new type[size]; creates the array with a fixed size.
- You can also initialize the array with values directly.
csharp
int[] numbers = new int[5]; string[] names = { "Alice", "Bob", "Charlie" };
Example
This example shows how to create an integer array, assign values, and print them.
csharp
using System; class Program { static void Main() { int[] numbers = new int[3]; numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; foreach (int number in numbers) { Console.WriteLine(number); } } }
Output
10
20
30
Common Pitfalls
Common mistakes when creating arrays in C# include:
- Forgetting to specify the size when using
new. - Trying to change the size of an array after creation (arrays have fixed size).
- Accessing indexes outside the array bounds, which causes errors.
Always remember arrays start at index 0.
csharp
int[] arr = new int[3]; // Wrong: arr = new int[0]; // Missing size // Wrong: arr[3] = 5; // Index out of range // Right: arr[0] = 1; arr[1] = 2; arr[2] = 3;
Quick Reference
Summary of array creation in C#:
| Syntax | Description |
|---|---|
type[] name = new type[size]; | Create array with fixed size |
type[] name = { val1, val2, ... }; | Create and initialize array |
name[index] | Access element at index (0-based) |
| Syntax | Description |
|---|---|
| type[] name = new type[size]; | Create array with fixed size |
| type[] name = { val1, val2, ... }; | Create and initialize array |
| name[index] | Access element at index (0-based) |
Key Takeaways
Use
type[] name = new type[size]; to create an array with a fixed size.You can initialize arrays directly with values using
type[] name = { val1, val2, ... };.Array indexes start at 0 and go up to size minus one.
Arrays in C# have a fixed size and cannot be resized after creation.
Always avoid accessing indexes outside the array bounds to prevent errors.