Arrays and Collections in C#: List, Dictionary, Queue & Stack Guide

1. Arrays and Collections Overview

Q: What are arrays in C#?

Arrays are fixed-size, ordered collections of elements of the same type, stored contiguously in memory. They are reference types in C#, allocated on the heap, and accessed using zero-based indices.

Syntax:

type[] arrayName = new type[size];

Q: What are collections in C#?

Collections are dynamic, flexible data structures provided by the .NET framework (in System.Collections.Generic) to store and manage multiple items. Unlike arrays, collections can grow or shrink dynamically. Common collections include List<T>, Dictionary<TKey, TValue>, Queue<T>, and Stack<T>.

Q: How do arrays and collections differ from C/C++?

2. Single and Multidimensional Arrays

Q: What are single-dimensional arrays in C#?

Single-dimensional arrays are linear collections of elements accessed with one index. They are declared with a fixed size and initialized explicitly or with values.

Syntax:

int[] numbers = new int[5]; // Declare array of size 5
int[] values = { 1, 2, 3, 4, 5 }; // Initialize with values

Q: What are multidimensional arrays in C#?

Multidimensional arrays store elements in a grid-like structure with multiple indices. C# supports:

Syntax:

int[,] matrix = new int[2, 3]; // 2x3 rectangular array
int[][] jagged = new int[2][]; // Jagged array with 2 sub-arrays

Q: Can you give an example of single and multidimensional arrays in C#?

using System;

namespace Arrays
{
    class Program
    {
        static void Main(string[] args)
        {
            // Single-dimensional array
            int[] numbers = { 10, 20, 30, 40, 50 };
            Console.WriteLine("Single-dimensional array:");
            for (int i = 0; i < numbers.Length; i++)
            {
                Console.WriteLine($"numbers[{i}] = {numbers[i]}");
            }

            // Rectangular array (2x3)
            int[,] matrix = {
                { 1, 2, 3 },
                { 4, 5, 6 }
            };
            Console.WriteLine("\nRectangular array:");
            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();
            }

            // Jagged array
            int[][] jagged = new int[2][];
            jagged[0] = new int[] { 1, 2 };
            jagged[1] = new int[] { 3, 4, 5 };
            Console.WriteLine("\nJagged array:");
            for (int i = 0; i < jagged.Length; i++)
            {
                Console.Write($"Row {i}: ");
                for (int j = 0; j < jagged[i].Length; j++)
                {
                    Console.Write($"{jagged[i][j]} ");
                }
                Console.WriteLine();
            }
        }
    }
}

Output:

Single-dimensional array:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50

Rectangular array:
1 2 3 
4 5 6 

Jagged array:
Row 0: 1 2 
Row 1: 3 4 5 

3. Generic Collections: List, Dictionary, Queue & Stack

Q: What is List<T> in C#?

List<T> is a generic, dynamic collection that stores elements of type T in an ordered, resizable list. It supports adding, removing, and accessing elements by index.

Syntax:

List<T> list = new List<T>();

Q: What is Dictionary<TKey, TValue> in C#?

Dictionary<TKey, TValue> is a generic collection that stores key-value pairs, allowing fast lookup by key. Keys must be unique, and elements are unordered.

Syntax:

Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();

Q: What is Queue<T> in C#?

Queue<T> is a generic collection that implements a first-in, first-out (FIFO) structure. Elements are added (Enqueue) at the back and removed (Dequeue) from the front.

Syntax:

Queue<T> queue = new Queue<T>();

Q: What is Stack<T> in C#?

Stack<T> is a generic collection that implements a last-in, first-out (LIFO) structure. Elements are added (Push) and removed (Pop) from the top.

Syntax:

Stack<T> stack = new Stack<T>();

Q: Can you give an example of List, Dictionary, Queue, and Stack in C#?

using System;
using System.Collections.Generic;

namespace Collections
{
    class Program
    {
        static void Main(string[] args)
        {
            // List
            List names = new List { "Krishna", "Kristal" };
            names.Add("Ram");
            Console.WriteLine("List:");
            foreach (string name in names)
            {
                Console.WriteLine(name);
            }

            // Dictionary
            Dictionary students = new Dictionary
            {
                { 101, "Krishna" },
                { 102, "Kristal" }
            };
            students[103] = "Ram";
            Console.WriteLine("\nDictionary:");
            foreach (var pair in students)
            {
                Console.WriteLine($"ID: {pair.Key}, Name: {pair.Value}");
            }

            // Queue
            Queue queue = new Queue();
            queue.Enqueue("Task 1");
            queue.Enqueue("Task 2");
            Console.WriteLine("\nQueue:");
            while (queue.Count > 0)
            {
                Console.WriteLine($"Dequeued: {queue.Dequeue()}");
            }

            // Stack
            Stack stack = new Stack();
            stack.Push("Item 1");
            stack.Push("Item 2");
            Console.WriteLine("\nStack:");
            while (stack.Count > 0)
            {
                Console.WriteLine($"Popped: {stack.Pop()}");
            }
        }
    }
}

Output:

List:
Krishna
Kristal
Ram

Dictionary:
ID: 101, Name: Krishna
ID: 102, Name: Kristal
ID: 103, Name: Ram

Queue:
Dequeued: Task 1
Dequeued: Task 2

Stack:
Popped: Item 2
Popped: Item 1

4. Common Mistakes & Best Practices

Q: Common mistakes?

Q: Best practices?