AnyCompiler

Arrays aur Lists

Ek C# array ka size creation ke time hi fix ho jata hai. foreach kisi bhi collection par — array ho ya List<T> — bina kisi index ke iterate kar sakta hai.

List<T>

List<T> C# ka primary growable collection hai, System.Collections.Generic se — jab aap Add se elements daalte ho to ye khud apna resizing manage karta hai, aur C# ke har generic collection ki tarah, <T> ka matlab hai ye type-safe hai: ek List<int> hamesha sirf ints hi rakh sakta hai.

using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        int[] numbers = { 4, 8, 15, 16, 23 };
        int sum = 0;
        foreach (int n in numbers) {
            sum += n;
        }
        Console.WriteLine(sum);

        List<int> list = new List<int>();
        list.Add(1);
        list.Add(2);
        list.Add(3);
        Console.WriteLine(list.Count);
    }
}
Output
66
3

Aage: strings — interpolation, aur Java se ek genuine difference: C# ka == string ka content compare karta hai, references nahi.

Practice exercise

int[] numbers = { 4, 8, 15, 16 } diya gaya hai, foreach loop se iske saare elements sum karo aur total print karo.