In modern software development, understanding how to loop over arrays in C# is one of the most essential programming skills. Arrays are foundational data structures in C# programming, and looping allows developers to access, manipulate, and process array elements efficiently. Whether you are building enterprise applications using .NET, creating games with Unity, or developing web APIs using ASP.NET Core, mastering array iteration in C# is critical.
This comprehensive guide explains how to loop through arrays in C#, covering different loop types such as for loop, foreach loop, while loop, do-while loop, and advanced iteration techniques using LINQ. By the end of this tutorial, you will clearly understand C# array iteration, performance considerations, best practices, and real-world examples.
An array in C# is a fixed-size collection of elements of the same data type. Arrays are zero-indexed, meaning the first element starts at index 0. Arrays are stored in contiguous memory locations, making them efficient for direct access.
using System;
class Program
{
static void Main()
{
int[] numbers = new int[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
}
}
int[] numbers = { 10, 20, 30, 40, 50 };
Now that we understand arrays, letβs explore how to loop through array in C# effectively.
The for loop is one of the most commonly used methods for C# array iteration. It provides full control over the index.
for (initialization; condition; increment)
{
// Code block
}
using System;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
}
}
Explanation:
The for loop is ideal when you need the index for operations such as modifying array values.
The C# foreach loop is designed specifically for iterating over collections like arrays. It simplifies syntax and improves readability.
foreach (dataType variable in arrayName)
{
// Code block
}
using System;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
}
}
Advantages of foreach:
However, foreach does not allow direct modification of array elements.
The while loop checks condition before execution. It is less commonly used for array iteration but still important.
using System;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
int i = 0;
while (i < numbers.Length)
{
Console.WriteLine(numbers[i]);
i++;
}
}
}
The do-while loop executes at least once before checking the condition.
using System;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
int i = 0;
do
{
Console.WriteLine(numbers[i]);
i++;
}
while (i < numbers.Length);
}
}
C# supports multidimensional arrays. Looping requires nested loops.
using System;
class Program
{
static void Main()
{
int[,] matrix = {
{1, 2, 3},
{4, 5, 6}
};
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
}
Language Integrated Query (LINQ) provides modern and expressive ways to iterate arrays.
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
var doubled = numbers.Select(n => n * 2);
foreach (var num in doubled)
{
Console.WriteLine(num);
}
}
}
When learning C# loop over arrays, understanding performance is important:
For high-performance applications, especially in game development or real-time systems, traditional for loops are preferred.
To modify elements, use for loop instead of foreach.
using System;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = numbers[i] * 10;
}
foreach (int num in numbers)
{
Console.WriteLine(num);
}
}
}
for (int i = 0; i <= numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
The condition should be i < numbers.Length, not less than or equal.
int[] numbers = null;
Console.WriteLine(numbers.Length);
Always check if array is null before iteration.
using System;
class Program
{
static void Main()
{
int[] marks = { 80, 75, 90, 85, 70 };
int sum = 0;
foreach (int mark in marks)
{
sum += mark;
}
double average = (double)sum / marks.Length;
Console.WriteLine("Average: " + average);
}
}
Arrays are fixed in size, while List provides dynamic resizing. If size is known and fixed, arrays are more memory-efficient. For dynamic collections, List is better.
Mastering C# array iteration is essential for any C# developer. Understanding how to loop through array in C# using for loop, foreach loop, while loop, and LINQ helps build efficient and clean programs. Each looping method has its use case, advantages, and performance implications.
Whether you are a beginner learning C# programming tutorial concepts or an experienced developer optimizing .NET applications, knowing how to properly iterate arrays in C# is fundamental to writing clean, efficient, and maintainable code.
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved