Arrays & Lists
Working with sequences of data
Introduction
In this lesson, you'll learn about arrays & lists in C#. Coming from C, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In C, you're familiar with working with sequences of data.
C# has its own approach to working with sequences of data, which we'll explore step by step.
The C# Way
Let's see how C# handles this concept. Here's a typical example:
using System.Collections.Generic;
using System.Linq;
// Fixed array
int[] nums = { 1, 2, 3, 4, 5 };
int n = nums.Length;
// Dynamic list (no malloc/free)
var list = new List<int> { 1, 2, 3 };
list.Add(4);
list.AddRange(new[] { 5, 6 });
list.Remove(3);
// Foreach
foreach (int x in nums) {
Console.WriteLine(x);
}
// LINQ — functional operations
int[] squared = nums.Select(x => x * x).ToArray();
int[] evens = nums.Where(x => x % 2 == 0).ToArray();
int total = nums.Sum();Comparing to C
Here's how you might have written similar code in C:
#include <stdio.h>
#include <stdlib.h>
/* Fixed array */
int nums[5] = {1, 2, 3, 4, 5};
int n = sizeof(nums)/sizeof(nums[0]);
/* Dynamic array — manual */
int *dyn = malloc(10 * sizeof(int));
dyn[0] = 42;
dyn = realloc(dyn, 20 * sizeof(int));
free(dyn);
/* Iteration */
for (int i = 0; i < n; i++) {
printf("%d\n", nums[i]);
}You may be used to different syntax or behavior.
C# List<T> is the dynamic array — no malloc/free needed
You may be used to different syntax or behavior.
C# arrays have .Length property; C needs sizeof division trick
You may be used to different syntax or behavior.
C# foreach replaces C's index-based for loop
You may be used to different syntax or behavior.
LINQ provides functional map/filter/reduce with no C equivalent
Step-by-Step Breakdown
1. List vs malloc
C#'s List<T> is a type-safe, garbage-collected dynamic array. It grows automatically — no malloc, realloc, or free.
int *dyn = malloc(10 * sizeof(int));
dyn = realloc(dyn, 20 * sizeof(int));
free(dyn);var list = new List<int>();
list.Add(1);
// grows automatically, GC frees it2. foreach
C#'s foreach iterates any IEnumerable without index management, reducing off-by-one errors common in C.
for (int i = 0; i < n; i++) printf("%d\n", arr[i]);foreach (int x in nums) Console.WriteLine(x);3. LINQ
LINQ adds SQL-like querying and functional operations (Select=map, Where=filter, Aggregate=reduce) to all collections.
var result = nums
.Where(x => x > 2)
.Select(x => x * x)
.ToList();Common Mistakes
When coming from C, developers often make these mistakes:
- C# List<T> is the dynamic array — no malloc/free needed
- C# arrays have .Length property; C needs sizeof division trick
- C# foreach replaces C's index-based for loop
Key Takeaways
- List<T> replaces malloc/realloc/free for dynamic arrays
- GC handles memory; no manual cleanup
- foreach over for(i=0;i<n;i++) for clarity
- LINQ provides functional query operations