CodeToLive

Arrays and Collections

Arrays and collections are fundamental data structures in C# that allow you to store and manage multiple values efficiently. They provide powerful ways to organize and manipulate data in your applications.

Arrays

Arrays are fixed-size collections of elements of the same type. They provide fast access to elements via index.


// Array declaration and initialization
int[] numbers = { 1, 2, 3, 4, 5 };
string[] names = new string[3] { "Alice", "Bob", "Charlie" };

// Accessing array elements
Console.WriteLine(numbers[0]); // Output: 1
Console.WriteLine(names[2]);   // Output: Charlie

// Iterating through an array
foreach (int num in numbers) {
    Console.WriteLine(num);
}
      

Lists

Lists are dynamic collections that can grow or shrink in size. They offer more flexibility than arrays.


// List declaration and initialization
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

// Adding elements
names.Add("David");
names.Insert(1, "Eve");

// Removing elements
names.Remove("Bob");
names.RemoveAt(0);

// Accessing elements
Console.WriteLine(names[2]); // Output: Charlie

// List methods
int count = names.Count;
bool contains = names.Contains("Alice");
      

Dictionaries

Dictionaries store key-value pairs, providing fast lookups by key. Each key must be unique.


// Dictionary declaration and initialization
Dictionary<string, int> ages = new Dictionary<string, int>();

// Adding elements
ages["Alice"] = 25;
ages.Add("Bob", 30);
ages.Add("Charlie", 35);

// Accessing elements
Console.WriteLine(ages["Alice"]); // Output: 25

// Checking for keys
if (ages.ContainsKey("Bob")) {
    Console.WriteLine("Bob's age: " + ages["Bob"]);
}

// Iterating through a dictionary
foreach (KeyValuePair<string, int> entry in ages) {
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}
      

Other Collection Types

C# provides several specialized collection types for different scenarios:

Best Practices

Next: Methods and Functions