← C# tutorial

C#

Arrays

An array holds a fixed number of same-typed values: int[] numbers = {1, 2, 3, 4, 5};.

Example: foreach over an array

using System;

class Program {
    static void Main() {
        int[] numbers = {1, 2, 3, 4, 5};
        int total = 0;
        foreach (int n in numbers) {
            total += n;
        }
        Console.WriteLine($"Total: {total}");
    }
}
Total: 15

foreach (int n in numbers) steps through each value in turn without needing a manual index, prefer it over a plain for loop whenever you don't specifically need the index itself. Get the count with numbers.Length (a property, no parentheses) if you do need to know the size.

Example
using System;

class Program {
    static void Main() {
        int[] numbers = {1, 2, 3, 4, 5};
        int total = 0;
        foreach (int n in numbers) {
            total += n;
        }
        Console.WriteLine($"Total: {total}");
    }
}
Output
Total: 15
Ready to go further?

These free tutorials are a preview of what a Code Secure Academy cohort covers, project work and all.

Explore our tracks
Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account