Naming a piece of work
A program of a few dozen lines can be read top to bottom. A program of a few thousand cannot, unless it is cut into pieces that each have a name, a clear job, and a stated contract: "give me these inputs and I will give you this result". In C# those pieces are methods.
Programs also hold many values at once: the names in a class register, the prices in a basket, the words in a document and how often each appears. For that, .NET provides a family of collections, each tuned for a different way of using data. Picking the right one is one of the most practical skills in everyday programming. Looking something up in the right collection takes the same time whether it holds ten items or ten million; in the wrong one, the program slows down as the data grows.
Methods
A method has a return type, a name, a parameter list and a body:
static double CircleArea(double radius)
{
return Math.PI * radius * radius;
}double before the name is what the method returns; void means it returns nothing. Each parameter has a type and a name. A method whose body is a single expression can use an expression body: static double CircleArea(double radius) => Math.PI * radius * radius;.
In a file with top-level statements, a method written among the statements is a local function. In larger programs, methods belong to types: static methods belong to the type itself and are called as Math.Max(a, b), while instance methods (the next lesson) belong to individual objects. A static class is a container for static methods only, like Math or Console.
This program shows the features you will use every day:
Console.WriteLine(Geometry.Area(3));
Console.WriteLine(Geometry.Area(3, 4));
Console.WriteLine(Geometry.Describe("garden", width: 12.5, length: 8));
Console.WriteLine(Geometry.Describe("rug", 2, 3, unit: "ft"));
var (low, high) = Stats.Range([18, 25, 21, 30, 16]);
Console.WriteLine($"Temperatures ranged from {low} to {high}.");
Console.WriteLine($"Total: {Stats.Sum(4, 8, 15, 16, 23, 42)}");
int a = 1, b = 2;
Stats.Swap(ref a, ref b);
Console.WriteLine($"After swap: a = {a}, b = {b}");
if (Stats.TryAverage([], out double avg))
Console.WriteLine($"Average {avg}");
else
Console.WriteLine("No average of an empty list.");
static class Geometry
{
// Overloads: same name, different parameter lists.
public static double Area(double side) => side * side;
public static double Area(double width, double length) => width * length;
// Optional parameters have defaults; callers may name arguments.
public static string Describe(string name, double width, double length, string unit = "m")
=> $"The {name} is {width} {unit} by {length} {unit}: {Area(width, length)} square {unit}.";
}
static class Stats
{
// A tuple returns two values without defining a type for them.
public static (int Min, int Max) Range(int[] values)
{
int min = values[0], max = values[0];
foreach (int v in values)
{
if (v < min) min = v;
if (v > max) max = v;
}
return (min, max);
}
// params collects any number of arguments; since C# 13 it can be a span.
public static int Sum(params ReadOnlySpan<int> numbers)
{
int total = 0;
foreach (int n in numbers) total += n;
return total;
}
// ref passes the variable itself, not a copy of its value.
public static void Swap(ref int x, ref int y) => (x, y) = (y, x);
// out: the "Try" pattern returns success and hands back a result.
public static bool TryAverage(int[] values, out double average)
{
if (values.Length == 0)
{
average = 0;
return false;
}
average = (double)Sum(values) / values.Length;
return true;
}
}It prints:
9
12
The garden is 12.5 m by 8 m: 100 square m.
The rug is 2 ft by 3 ft: 6 square ft.
Temperatures ranged from 16 to 30.
Total: 108
After swap: a = 2, b = 1
No average of an empty list.Taking the pieces in turn:
- Overloading. Two methods may share a name if their parameter lists differ. The compiler picks the best match for each call:
Area(3)calls the one-parameter version. (Local functions cannot be overloaded, which is one reason these methods live in static classes. Type declarations must come after the top-level statements in the file.) - Optional and named arguments.
unit = "m"gives a default, so callers may leave it out. Arguments can be passed by name (width: 12.5), which makes calls with several numbers of the same type much easier to read and harder to get wrong. - Tuples.
(int Min, int Max)is a lightweight pair with named elements. The caller can take it apart with deconstruction:var (low, high) = .... Tuples are perfect for returning two or three values from a private helper; for anything that travels further, define a record (a later lesson) so the type has a name. params. It lets a method take any number of arguments, written as a plain list. Before C# 13 aparamsparameter had to be an array; now it can be a span or a collection type, which avoids allocating an array for each call.ref. Normally an argument is copied into the parameter. Withref, the method receives the caller's variable itself, so assigning to it changes the caller's variable.(x, y) = (y, x)swaps two values using a tuple. Userefsparingly: it makes data flow harder to follow.outand the Try pattern. Anoutparameter must be assigned by the method before it returns. The .NET conventionbool TryX(..., out T result)reports whether an operation succeeded without throwing an exception: you metint.TryParsein the previous lesson, andDictionaryhasTryGetValue. The empty collection expression[]passes an empty array.
Definition— Pass by value
C# copies each argument into its parameter unless the parameter is marked ref, out or in. For a value type the copy is the data itself; for a reference type (an array, a list, any class) the copy is a reference, so the method sees the same object and can change its contents, but cannot make the caller's variable point at a different object.
That last sentence surprises many beginners: passing an array "by value" still lets the method change the array's elements. Exercise 2 below checks that you have it.
Recursion and local functions
A method may call itself. Recursion fits problems that contain smaller copies of themselves: Euclid's algorithm for the greatest common divisor, or walking a tree of folders inside folders.
// Recursion: Euclid's algorithm for the greatest common divisor.
static int Gcd(int a, int b) => b == 0 ? a : Gcd(b, a % b);
Console.WriteLine($"gcd(1071, 462) = {Gcd(1071, 462)}");
// A recursive function that walks a nested structure: the total size of a folder tree.
static long TotalSize(Folder folder)
{
long total = 0;
foreach (long size in folder.FileSizes) total += size;
foreach (Folder child in folder.Children) total += TotalSize(child);
return total;
}
Folder photos = new("photos", [2_400_000, 3_100_000], []);
Folder notes = new("notes", [12_000, 8_500, 30_000], []);
Folder home = new("home", [1_000], [photos, notes]);
Console.WriteLine($"{home.Name} holds {TotalSize(home):N0} bytes");
record Folder(string Name, long[] FileSizes, Folder[] Children);It prints:
gcd(1071, 462) = 21
home holds 5,551,500 bytesThe last line declares Folder as a record with three properties, in one line; the lesson on classes and records explains everything it does. The format N0 prints a number with thousands separators and no decimals.
The local functions here are marked static, which means they cannot accidentally use variables from the surrounding code: everything they need arrives as a parameter. It is a good habit for small helpers.
Every recursive call uses a little space on the thread's call stack, which is fixed in size (typically between 1 and 8 MB, depending on the operating system and thread). Recursion as deep as a tree is tall is fine; recursion as deep as a list is long (a million calls) will crash with a stack overflow, which in .NET cannot be caught. C# does not promise to turn tail calls into loops, so write deep, linear processes as loops.
The everyday collections
The System.Collections.Generic namespace (imported automatically) holds the collections you will use most. They are generic: the type in angle brackets says what they hold, so a List<string> holds only strings, and you never need to cast what comes out.
// Arrays have a fixed length; List<T> grows.
string[] weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"];
Console.WriteLine($"{weekdays.Length} weekdays, the third is {weekdays[2]}");
List<string> choir = ["Amara", "Bao", "Chiara"];
choir.Add("Dmitri");
choir.Insert(0, "Yusuf");
choir.Remove("Bao");
choir.Sort();
Console.WriteLine($"Choir ({choir.Count}): {string.Join(", ", choir)}");
Console.WriteLine($"Is Chiara in the choir? {choir.Contains("Chiara")}");
// Dictionary<TKey, TValue>: look things up by key.
string text = "the cat saw the dog and the dog saw the cat run";
Dictionary<string, int> counts = [];
foreach (string word in text.Split(' '))
{
counts[word] = counts.GetValueOrDefault(word) + 1;
}
foreach (var (word, count) in counts)
{
Console.WriteLine($"{word,-4} {new string('*', count)}");
}
if (counts.TryGetValue("bird", out int birds))
Console.WriteLine($"bird: {birds}");
else
Console.WriteLine("no birds in this text");
// HashSet<T>: membership and set algebra.
HashSet<string> speaksFrench = ["Awa", "Luc", "Mariam"];
HashSet<string> speaksArabic = ["Mariam", "Omar", "Awa"];
HashSet<string> both = [.. speaksFrench];
both.IntersectWith(speaksArabic);
Console.WriteLine($"Speak both: {string.Join(", ", both.Order())}");
// Collection expressions can spread other collections with ..
int[] morning = [7, 8, 9];
int[] evening = [17, 18];
int[] busyHours = [.. morning, 12, .. evening];
Console.WriteLine($"Busy hours: {string.Join(" ", busyHours)}");It prints:
5 weekdays, the third is Wed
Choir (4): Amara, Chiara, Dmitri, Yusuf
Is Chiara in the choir? True
the ****
cat **
saw **
dog **
and *
run *
no birds in this text
Speak both: Awa, Mariam
Busy hours: 7 8 9 12 17 18- An array (
string[]) has a fixed length chosen when it is created. It is the simplest and fastest collection, and the right choice when the size is known. - A
List<string>is a growable array.Addputs an item at the end,InsertandRemoveshift the items after them,Sortsorts in place, andCount(notLength) tells you how many there are. - A
Dictionary<string, int>maps keys to values using a hash table.counts[word] = ...adds or replaces; readingcounts[word]for a missing key throws, so useTryGetValueorGetValueOrDefaultwhen the key may be absent. Iterating gives key-value pairs, whichvar (word, count)deconstructs. - A
HashSet<string>stores each value once and answers "is this in the set?" quickly. It also does set algebra:IntersectWith,UnionWith,ExceptWith.Order()returns the items sorted, because a hash set has no meaningful order of its own. - Collection expressions (C# 12) create any of these with the same square brackets.
[]is empty, and the spread element..copies in all the items of another collection.
The other three you will reach for are small but important:
// Queue<T>: first in, first out.
Queue<string> printJobs = new();
printJobs.Enqueue("report.pdf");
printJobs.Enqueue("photo.jpg");
printJobs.Enqueue("ticket.png");
while (printJobs.Count > 0)
{
Console.WriteLine($"printing {printJobs.Dequeue()}");
}
// Stack<T>: last in, first out, the shape of an undo history.
Stack<string> undo = new();
undo.Push("type 'Hello'");
undo.Push("make bold");
undo.Push("insert image");
Console.WriteLine($"undo: {undo.Pop()}");
Console.WriteLine($"undo: {undo.Pop()}");
Console.WriteLine($"next undo would be: {undo.Peek()}");
// PriorityQueue<TElement, TPriority>: the smallest priority comes out first.
PriorityQueue<string, int> triage = new();
triage.Enqueue("sprained ankle", 3);
triage.Enqueue("chest pain", 1);
triage.Enqueue("cough", 4);
triage.Enqueue("deep cut", 2);
while (triage.TryDequeue(out string? patient, out int priority))
{
Console.WriteLine($"priority {priority}: {patient}");
}
// Changing a collection while enumerating it is an error.
List<int> numbers = [1, 2, 3, 4];
try
{
foreach (int n in numbers)
{
if (n % 2 == 0) numbers.Remove(n);
}
}
catch (InvalidOperationException e)
{
Console.WriteLine($"Error: {e.Message}");
}
numbers.RemoveAll(n => n % 2 == 0);
Console.WriteLine($"After RemoveAll: {string.Join(", ", numbers)}");It prints:
printing report.pdf
printing photo.jpg
printing ticket.png
undo: insert image
undo: make bold
next undo would be: type 'Hello'
priority 1: chest pain
priority 2: deep cut
priority 3: sprained ankle
priority 4: cough
Error: Collection was modified; enumeration operation may not execute.
After RemoveAll: 1, 3The last part is a trap every C# programmer falls into once. foreach walks a collection with an enumerator, and the standard collections detect being changed underneath it and throw rather than skip or repeat items. Remove the first even number, 2, and the very next step of the loop throws; 4 is never examined, which is why it is still there for RemoveAll to remove. Either collect what to remove and remove it afterwards, loop backwards by index, or use RemoveAll with a condition, as the last lines do. (n => n % 2 == 0 is a lambda, a small inline function; LINQ, two lessons from now, is built on them.) The string? in the triage loop is a nullable annotation, explained in the lesson on nullable reference types.
What each operation costs
| Collection | Look up by position | Find a value | Add | Remove |
|---|---|---|---|---|
| Array | not possible | not possible | ||
List<int> | amortised at the end | |||
Dictionary<string, int> | none | average, by key | average | average |
HashSet<string> | none | average | average | average |
Queue<string>, Stack<string> | ends only | amortised | at the end that is served | |
PriorityQueue<string, int> | smallest only | none | for the smallest |
So choir.Contains scans the whole list, while a HashSet answers in about the same time whatever its size. If a program checks "have I seen this before?" in a loop over a large input, using a list instead of a set turns a linear algorithm into a quadratic one. When you need keys kept in order, use SortedDictionary or SortedSet (balanced trees, ).
How professionals write methods
The compiler accepts almost any method. Colleagues are pickier. Conventions that nearly every C# codebase follows:
- Naming. Methods, types and properties use PascalCase (
CalculateTotal,TryAverage); parameters and local variables use camelCase (openingDeposit). A method's name starts with a verb and says what it does or returns; aboolmethod or property reads like a question (IsEmpty,HasExpired,CanWithdraw). - Small and single-purpose. A method that fits on one screen and does one thing is easy to test and to reuse. When you find yourself writing a comment like
// now compute the tax, that part probably wants to be its own method with that name. - Guard the door. Check arguments at the start and leave early (
if (values.Length == 0) return ...;). Code that handles the odd cases first and then the normal case without deep nesting is easier to follow than a pyramid ofifblocks. - Avoid boolean flag parameters. A call such as
Export(report, true, false)tells the reader nothing. Use named arguments, anenum, or two methods with different names (ExportAsPdf,ExportAsCsv). - Accept the most general input, return the most specific output. A method that only reads a sequence should accept
IEnumerable<string>orIReadOnlyList<string>so callers can pass an array, a list or a query; a method that builds a list can returnList<string>so callers get its full abilities. - Document the public surface. Comments that start with
///are XML documentation comments; editors show them when someone hovers over a call, and tools turn them into reference documentation.
/// <summary>Returns the smallest and largest of the values.</summary>
/// <exception cref="ArgumentException">The array is empty.</exception>
public static (int Min, int Max) Range(int[] values) { ... }None of these rules is enforced by the language, but many are checked by the analyzers that ship with the .NET SDK and by the .editorconfig file a team keeps in its repository, which the last lesson of this course covers.
Common misconceptions
Misconception
"Passing a list to a method gives the method its own copy." It gives the method a copy of the reference. Both point at one list, so Add or Clear inside the method affects the caller. If a method should not modify its input, accept an IReadOnlyList<string> or IEnumerable<string> (the next lessons explain these interfaces), or copy explicitly.
Misconception
"A dictionary keeps items in the order I added them." Today's Dictionary often appears to, as long as you never remove anything, but the documentation does not promise it, and code that depends on it breaks quietly. If order matters, sort when you read, or use SortedDictionary or the OrderedDictionary type added in .NET 9.
Misconception
"out and ref are how you return several values." Modern C# uses tuples or records for that. Keep out for the Try pattern and ref for the rare cases where performance or an existing API requires it.
Exercises
1. Methods, arrays and collections
Warm-upComputationalWhat does this program print?
static void AddOne(int x) => x++;
static void AddOneRef(ref int x) => x++;
int n = 5;
AddOne(n);
AddOneRef(ref n);
AddOneRef(ref n);
Console.WriteLine(n);
2. Methods, arrays and collections
CoreComputationalWhat does this program print?
static void Zero(int[] values) => values[0] = 0;
int[] data = [5, 6, 7];
Zero(data);
Console.WriteLine(data[0] + data[1]);
3. Methods, arrays and collections
CoreComputationalWhat does this program print?
Dictionary<char, int> counts = [];
foreach (char c in "banana")
{
counts[c] = counts.GetValueOrDefault(c) + 1;
}
Console.WriteLine($"{counts.Count} {counts['a']}");
4. Methods, arrays and collections
CoreComputationalWhat does this program print?
Stack<int> stack = new();
Queue<int> queue = new();
foreach (int i in new[] { 1, 2, 3 })
{
stack.Push(i);
queue.Enqueue(i);
}
Console.WriteLine($"{stack.Pop()}{queue.Dequeue()}{stack.Pop()}{queue.Dequeue()}");
5. Methods, arrays and collections
Warm-upComputationalWhat does this program print?
static string Label(string item, int quantity = 1, string unit = "piece")
=> $"{quantity} {unit} of {item}";
Console.WriteLine(Label("rice", unit: "kg"));
6. Methods, arrays and collections
CoreComputationalWhat does this program print?
static int F(int n) => n <= 1 ? 1 : n * F(n - 2);
Console.WriteLine(F(7));
7. Methods, arrays and collections
CoreHumanA mail service reads ten million incoming addresses and must flag each one it has already seen earlier in the stream. Which collection should hold the addresses seen so far?
Further reading and resources
- Methods (C# programming guide) · MicrosoftParameters, return values, overloading and more.
- Collections · MicrosoftAn overview of the collection types in .NET and when to use each.
- Collection expressions · MicrosoftThe square-bracket syntax for creating collections, and the spread element.
- dotnet/runtimeThe source of the .NET runtime and base class library, including every collection in this lesson.