404 Not Found

404 Not Found


nginx

Arrays

One-Dimensional Array Declaration and Initialization

Arrays in C# are reference types stored on the heap. Declare an array using the type followed by square brackets, with zero-based indexing.

Example

CSHARP
int[] nums1 = new int[5];
int[] nums2 = new int[5] { 10, 20, 30, 40, 50 };
int[] nums3 = { 1, 2, 3, 4, 5 };
string[] names = { "Alice", "Bob", "Carol" };

Console.WriteLine(nums1[0]);
Console.WriteLine(nums2[2]);
Console.WriteLine(nums3.Length);
Console.WriteLine(names[1]);
▶ Try it Yourself
TEXT
0
30
5
Bob

Warning: new int[5] creates an array whose elements are automatically initialized to default values (0 for int, null for string).

Index Access and Bounds Checking

C# arrays are accessed by index, and the runtime performs bounds checking. An out-of-range index throws IndexOutOfRangeException, unlike undefined behavior in C.

Example

CSHARP
int[] nums = { 10, 20, 30, 40, 50 };

nums[0] = 99;
Console.WriteLine(nums[0]);
Console.WriteLine(nums[nums.Length - 1]);

try
{
    int val = nums[5];
}
catch (IndexOutOfRangeException)
{
    Console.WriteLine("Index out of range!");
}
▶ Try it Yourself
TEXT
99
50
Index out of range!

Tip: Use the Length property to get the array length, rather than sizeof as in C.

Common Array Class Methods

The Array class provides static methods for sorting, reversing, searching, copying, and more.

Example

CSHARP
int[] nums = { 5, 3, 8, 1, 9, 2 };

Array.Sort(nums);
Console.WriteLine(string.Join(", ", nums));

Array.Reverse(nums);
Console.WriteLine(string.Join(", ", nums));

int idx = Array.IndexOf(nums, 8);
Console.WriteLine(idx);

int[] copy = new int[3];
Array.Copy(nums, copy, 3);
Console.WriteLine(string.Join(", ", copy));

Array.Clear(nums, 0, 2);
Console.WriteLine(string.Join(", ", nums));

Array.Resize(ref nums, 8);
Console.WriteLine(nums.Length);
▶ Try it Yourself
TEXT
1, 2, 3, 5, 8, 9
9, 8, 5, 3, 2, 1
1
9, 8, 5
0, 0, 5, 3, 2, 1
8

Tip: Clear sets elements in the specified range to their default values rather than removing them. Resize can change the array length.

Multidimensional Arrays (Rectangular Arrays)

Multidimensional arrays, also called rectangular arrays, have the same length for every row. Use commas to separate dimensions in the declaration, e.g. int[,] for a 2D array.

Example

CSHARP
int[,] matrix = new int[3, 4];
matrix[0, 0] = 1;
matrix[1, 2] = 5;
matrix[2, 3] = 9;

int[,] grid = {
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

Console.WriteLine(grid[0, 1]);
Console.WriteLine(grid[2, 0]);
Console.WriteLine(grid.Length);
Console.WriteLine(grid.Rank);
▶ Try it Yourself
TEXT
2
7
9
2

Tip: Rank returns the number of dimensions, while Length returns the total number of elements (the product of all dimensions).

Jagged Arrays

A jagged array is an array of arrays, where each row can have a different length. Declare it with multiple sets of square brackets.

Example

CSHARP
int[][] jagged = new int[3][];
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5, 6 };
jagged[2] = new int[] { 7, 8, 9 };

Console.WriteLine(jagged[0].Length);
Console.WriteLine(jagged[1][2]);
Console.WriteLine(jagged[2][0]);

int[][] scores = {
    new int[] { 90, 85 },
    new int[] { 78, 92, 88 },
    new int[] { 95 }
};

Console.WriteLine(scores[1][1]);
▶ Try it Yourself
TEXT
2
5
7
92

Warning: Jagged arrays differ from rectangular arrays: int[,] is a contiguous 2D array in memory, while int[][] is a 1D array whose elements are independent arrays.

Iterating Arrays with foreach

The foreach statement simplifies array traversal by eliminating manual index management. It is suitable for read-only iteration.

Example

CSHARP
string[] fruits = { "Apple", "Banana", "Orange", "Grape" };

foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

int[,] matrix = {
    { 1, 2, 3 },
    { 4, 5, 6 }
};

foreach (int val in matrix)
{
    Console.Write(val + " ");
}
Console.WriteLine();
▶ Try it Yourself
TEXT
Apple
Banana
Orange
Grape
1 2 3 4 5 6

Tip: You cannot modify array elements inside a foreach loop. Use a for loop if you need to change values.

Arrays as Method Parameters

Arrays are reference types, so passing an array to a method passes the reference. Modifications to array elements inside the method affect the original array.

Example

CSHARP
void PrintArray(int[] arr)
{
    foreach (int n in arr)
    {
        Console.Write(n + " ");
    }
    Console.WriteLine();
}

void DoubleValues(int[] arr)
{
    for (int i = 0; i < arr.Length; i++)
    {
        arr[i] *= 2;
    }
}

int[] nums = { 1, 2, 3, 4, 5 };
PrintArray(nums);
DoubleValues(nums);
PrintArray(nums);

int Sum(int[] arr)
{
    int total = 0;
    foreach (int n in arr)
    {
        total += n;
    }
    return total;
}

Console.WriteLine(Sum(nums));
▶ Try it Yourself
TEXT
1 2 3 4 5
2 4 6 8 10
30

Warning: Because arrays are passed by reference, changes made by DoubleValues are directly reflected in the caller's array.

❓ FAQ

Q How do C# arrays differ from C arrays?
A C# arrays are reference types with built-in bounds checking that throws exceptions on out-of-range access; C arrays use pointer syntax, and out-of-bounds access is undefined behavior.
Q What do the Length and Rank properties return?
A Length returns the total number of elements, and Rank returns the number of dimensions.
Q When should I use a jagged array vs. a multidimensional array?
A Use multidimensional arrays when every row has the same length for a more compact layout; use jagged arrays when rows have different lengths.
Q Can foreach modify array elements?
A No, foreach is read-only iteration. Use a for loop if you need to modify element values.
Q Does Array.Resize create a new array?
A Yes, Resize creates a new array and copies the elements, replacing the original array reference.

📖 Summary

📝 Exercises

  1. Declare an array of 10 integers, assign values 1 through 10 using a loop, then print all elements in reverse order
  2. Use Array.Sort to sort a string array alphabetically, then print the result
  3. Create a 3x3 2D integer array, compute and print the sum of the diagonal elements
  4. Create a jagged array storing grades for 3 students (each with a different number of subjects), then compute each student's average score
  5. Write a method int FindMax(int[] arr) that accepts an array and returns the maximum value
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏