Appearance
C# primer for Last Perimeter
This page is optional. The course expects an intermediate C# developer. If a chapter uses a feature that you have not met, find it here, read the short explanation, then go back to the chapter.
Each entry says what the feature is, shows a small example from the course code, and names the chapter where you first meet it. The examples are short on purpose. The chapter shows the full code in context.
You do not type along on this page, and it has no tests. Read it in any order. The headings are stable, so a chapter can link straight to one entry.
Contents
- Functions as values: lambda expressions, expression-bodied members, Func and Action delegates, closures
- Collections: LINQ queries, deferred execution, two-dimensional arrays, tuples and deconstruction
- Types: records and the with expression, sealed classes and records, abstract classes, readonly record structs, required and init, generic constraints, extension methods
- Null handling: nullable reference types, null-coalescing and null-conditional operators
- Choosing between cases: switch expressions, patterns and when guards
- Lifetime: Lazy initialisation, IDisposable and using
- Tests: Fact tests, Theory and InlineData
- Where to read more
Functions as values
The course passes small pieces of behaviour around as values. This is how a test hands a fake keyboard to the input code, and how the host hands the clock to the services. The four entries below build on each other.
Lambda expressions
A lambda expression is a function with no name, written inline. The arrow => separates the parameters on the left from the body on the right. You use one when a method wants a function as an argument and a full named method would be noise.
A lambda is not the same thing as an expression-bodied member, although both use =>. A lambda is a value you can pass to a method. An expression-bodied member is a method or property written in short form. The next entry covers that one.
csharp
Assert.Throws<ArgumentException>(() => GameLaunchOptions.Parse(["--smoke-test-seconds"]));The () means the lambda takes no parameters. The test passes the lambda so that Assert.Throws can run it inside its own try block and catch the exception.
You first meet this in Chapter 01. A lambda with a parameter appears in Chapter 06, where segment => new[] { segment.Start, segment.End } turns each segment into two points.
Expression-bodied members
An expression-bodied member is a method, property or constructor whose whole body is one expression. You write => after the signature instead of braces and return. It is shorter, and it works best when the member does one small thing.
csharp
public int TileCount => Tiles.Count;This is a read-only property. Each time you read TileCount, it returns the current Tiles.Count. It has no field behind it and it does not store a copy.
Here => is not a lambda. Nothing is passed anywhere. You first meet this in Chapter 03.
Func and Action delegates
A delegate is a type that holds a method. Func<T> holds a method that takes no arguments and returns a T. Action<T> holds a method that takes one T and returns nothing. With more type arguments, Func lists the parameters first and the return type last, so Func<int, string> takes an int and returns a string.
The course uses them to inject behaviour. Code that needs the keyboard asks for a Func<KeyboardState> instead of calling the real keyboard. A test then passes a lambda that returns a fixed value.
csharp
private readonly Func<KeyboardState>? _readKeyboard;csharp
InputManager input = new(() => keyboard, () => default);The first line is a field that holds the function. The second line is a test giving the manager two lambdas. The tests need no real keyboard and no window.
Func first appears in Chapter 04. Action first appears in Chapter 05, in a test scene that runs a callback on each update. GameServices later takes an Action<string> that sets the window title.
Closures
A closure is a lambda that uses a variable from the method around it. The lambda does not copy the value. It keeps a reference to the variable itself. If the variable changes later, the lambda sees the new value the next time it runs.
csharp
KeyboardState keyboard = new(Keys.Enter);
InputManager input = new(() => keyboard, () => default);
input.GetCurrentInput(); // the lambda returns Enter held
keyboard = default; // change the variable
input.GetCurrentInput(); // the lambda now returns nothing heldThis is how the input tests simulate a key press and release. The test changes keyboard between calls, and the same lambda reports the new state each time. This code is modelled on PressedEdge_IsTrueForOneFrameOnly from the course.
A closure also has a cost. The compiler builds a hidden object to hold the captured variable, and that object lives on the heap. For this reason the course keeps lambdas out of the per-frame hot paths.
You first meet closures in Chapter 04, in the input tests.
Collections
LINQ queries
LINQ is a set of extension methods on collections, in the System.Linq namespace. They let you describe what you want from a collection instead of writing a loop. The course uses these ones.
| Method | What it does |
|---|---|
Where | Keeps the items that pass a test. |
Select | Turns each item into something else. |
OrderBy | Sorts the items by a key. |
First | Returns the first item, and throws if there is none. FirstOrDefault returns null instead. |
Any | Returns true if at least one item passes a test. |
Count | Counts the items, or only the ones that pass a test. |
ToList | Runs the query now and stores the result in a List<T>. |
csharp
RegionAnalysis? enemyFreeRegion = analyses.FirstOrDefault(analysis => analysis.EnemyIndexes.Count == 0);csharp
return _segments.Count(segment => Vector2.DistanceSquared(segment.Start, node) <= tolerance * tolerance);Each argument is a lambda that receives one item and returns a bool. LINQ allocates objects, so the course avoids it in code that runs every frame. It uses LINQ in set-up code and in tests.
You first meet LINQ in Chapter 06. The FirstOrDefault example is from Chapter 09.
Deferred execution
Most LINQ methods do not run when you call them. Where, Select and OrderBy build a description of the query and return at once. The work happens later, when you loop over the result or call a method that needs every item, such as ToList or Count.
This matters because the query reads the source at that later moment. If the source changes in between, the query sees the change.
csharp
List<int> numbers = [1, 2, 3];
IEnumerable<int> big = numbers.Where(n => n > 1); // nothing has run yet
numbers.Add(4);
int count = big.Count(); // runs now: 2, 3 and 4, so 3ToList ends the deferral. The course calls it when it wants a fixed copy, as in _segments = segments.ToList(); in Chapter 06. After that call, later changes to the original segments do not affect _segments.
Two-dimensional arrays
A two-dimensional array, written T[,], is one block of memory that you index with two numbers. The course uses it for the tile grid, so grid[x, y] is the tile in column x and row y. It is not an array of arrays. Every row has the same length, and the whole grid is one object.
csharp
private readonly TileState[,] _grid;
...
bool[,] visited = new bool[_arenaSystem.GridWidth, _arenaSystem.GridHeight];The array is created with the width first and the height second. Use GetLength(0) for the width and GetLength(1) for the height when you need them. A copy of the grid is a plain copy of the array, which the capture code uses to solve a capture without touching the live grid.
You first meet it in Chapter 03.
Tuples and deconstruction
A tuple groups two or more values without declaring a type. You write (int Y, int StartX, int EndX) for a tuple with named parts. It suits a short-lived group of values that only one method uses.
Deconstruction splits a tuple back into separate variables. You can declare new variables, or assign to variables that already exist.
csharp
List<(int Y, int StartX, int EndX)> ordered = group.OrderBy(segment => segment.StartX).ToList();csharp
(requiredClaim, speedMultiplier) = difficulty switch
{
DifficultyPreset.Chill => (Math.Max(70f, requiredClaim - 5f), speedMultiplier * 0.9f),
_ => (requiredClaim, speedMultiplier),
};The second example builds a tuple on the right and assigns both parts on the left in one step. It also shows a switch expression, which has its own entry below.
Tuples first appear in Chapter 06. The deconstruction (PendingKind kind, Scene? scene) = _pending[index]; appears in Chapter 17, and the assignment form is in Chapter 14.
Types
Records and the with expression
A record is a class, or a struct, that is built for holding data. The compiler writes equality for you, so two records with the same values are equal. It also writes a readable ToString. A positional record puts the properties in the declaration.
csharp
public sealed record CapturedZone(
int Order,
IReadOnlyList<Point> Tiles,
bool IsSlowDraw);A with expression copies a record and changes some properties. The original is not touched. This is how the course builds a level's configuration from the base one.
csharp
GameConfig config = baseConfig with
{
WinClaimPercentage = definition.RequiredClaimPercentage,
};config is a new GameConfig with the same values as baseConfig, except the ones you list. You first meet records in Chapter 01, and with in Chapter 14.
Sealed classes and records
sealed means that no other type can inherit from this one. The course marks almost every concrete class and record sealed. It tells the reader that the type is complete and that nothing overrides its behaviour. It also lets the runtime make some calls faster.
csharp
public sealed class LastPerimeterApp : Microsoft.Xna.Framework.GameA sealed class can still inherit from another class. It only stops anything inheriting from it. If you ever need to extend a sealed type, remove sealed first and decide what the subclass may change. You first meet it in Chapter 01.
Abstract classes
An abstract class cannot be created with new. It exists to be a base for other classes. It can declare abstract members, which have no body and which every subclass must supply.
csharp
public abstract class Scene : IDisposable
{
public abstract void Update(float deltaTime, InputState input);
public abstract void Draw(SpriteBatch spriteBatch);
}Every screen in the game is a Scene. The scene manager works with the base type and does not know which screen it holds. The compiler refuses to build a scene that forgets Update or Draw. You first meet it in Chapter 05.
Readonly record structs
A struct is a value type. It is copied when you pass it around, and it does not need a separate allocation on the heap. readonly says that no field changes after construction. record struct adds the equality and with support that records have.
csharp
public readonly record struct PathSegment(Vector2 Start, Vector2 End)The course uses this form for small values that it creates often, such as an input snapshot or one segment of a path. Because the value cannot change, no other code can alter it behind your back. Because it is a struct, creating one each frame does not add work for the garbage collector.
PathSegment appears in Chapter 02. Chapter 04 explains InputState in more detail.
Required and init
An init accessor is a setter that works only while the object is being created. You can set the property in an object initialiser, new Thing { Name = "x" }, and nowhere else afterwards. The object ends up read-only once construction finishes.
A required member must be set by whoever creates the object. If they forget, the code does not compile.
csharp
public required Player Player { get; init; }Together they give you an object that is complete when it is built and unchanged afterwards. If you create a GameSession without a player, the build fails with required member 'Player' must be set.
You first meet init in Chapter 03, and required in Chapter 05.
Generic constraints
A generic method works with any type that you give it. A constraint, written with where, limits which types are allowed. The compiler then lets the method use what the constraint guarantees.
csharp
private static TEnum Cycle<TEnum>(TEnum value, int direction) where TEnum : struct, EnumHere TEnum : struct, Enum means that the type must be a value type and also an enum. That one method can step any option, such as a theme or a difficulty, to the next value, and it will not compile for a string. A second example, where TEvent : GameEvent, only allows types that derive from GameEvent.
You first meet constraints in Chapter 11, with where TEvent : GameEvent. The enum form is in Chapter 17.
Extension methods
An extension method is a static method that you call as if it belonged to another type. The first parameter has this in front of it, and it names the type that gains the method. You can add methods to a type you do not own, such as an enum.
csharp
public static Direction Opposite(this Direction direction) => direction switch
{
Direction.Up => Direction.Down,
Direction.Down => Direction.Up,
Direction.Left => Direction.Right,
Direction.Right => Direction.Left,
_ => Direction.None,
};You write direction.Opposite(). The method has to live in a static class, and its namespace has to be in scope. LINQ is built from extension methods in the same way. You first meet them in Chapter 04.
Null handling
Nullable reference types
With nullable reference types switched on, a reference type such as string means "never null". Add ? and it means "may be null". The compiler then warns you if you use a possibly-null value without checking it. The course builds with zero warnings, so each warning is a prompt to think.
csharp
public static GameLaunchOptions Parse(string[] args, string? smokeTestSecondsEnvironmentValue = null)The ? on string? says the caller may pass nothing. Inside the method, you have to deal with null before you call a member on that parameter. The ? is a note for the compiler. It does not change how the program runs.
Do not confuse this with int?, which is a different feature. For a value type, ? really does change the type, to Nullable<int>. You first meet nullable reference types in Chapter 01.
Null-coalescing and null-conditional operators
?? gives you a fallback. It returns the left side, unless that is null, and then it returns the right side. ?. stops a member access when the left side is null, and gives null for the whole expression instead of throwing.
csharp
_launchOptions = launchOptions ?? new GameLaunchOptions(null);csharp
_cache?.Dispose();The first line uses the argument if there is one, and builds a default if not. The second line calls Dispose only if _cache exists. You can combine them: nearestSegment?.Snap(point) ?? point asks the segment to snap the point, and falls back to the original point when there is no segment.
On the right of ?? you can also put throw. The launch options do this, so a bad value stops the game with a clear message.
You first meet ?? in Chapter 01, and ?. in Chapter 02.
Choosing between cases
Switch expressions
A switch expression chooses a value. Each arm has a pattern on the left, =>, and a result on the right. The first arm that matches wins. The _ arm matches anything, so it acts as the default.
csharp
public static Microsoft.Xna.Framework.Vector2 ToVector(this Direction direction) => direction switch
{
Direction.Up => new Microsoft.Xna.Framework.Vector2(0f, -1f),
Direction.Down => new Microsoft.Xna.Framework.Vector2(0f, 1f),
_ => Microsoft.Xna.Framework.Vector2.Zero,
};This differs from the older switch statement. A statement runs code in each case. An expression produces a value, and the compiler checks that every possible input is covered. If you leave out the _ arm and miss a case, you get a warning.
You first meet switch expressions in Chapter 04.
Patterns and when guards
A pattern tests the shape of a value. The is keyword applies one. The patterns in the course include type, constant, null and not null.
csharp
if (_launchOptions.AutoExitAfter is TimeSpan autoExitAfter && gameTime.TotalGameTime >= autoExitAfter)csharp
else if (level.Fuse.IsWarning && session.Player.CurrentTrail is not null)The first line tests that a nullable value holds a TimeSpan, and names it autoExitAfter for use afterwards. The second line tests for not null.
A property pattern tests properties of the value inside braces. The course does not use one, but this is the form: trail is { IsSlowDraw: true } is true when trail is not null and its IsSlowDraw is true.
A when guard adds a condition to a case or a switch arm. The arm matches only if the pattern matches and the guard is true.
csharp
variants.Add(index switch
{
1 when levelNumber >= 4 => EnemyVariant.Hunter,
2 when levelNumber >= 7 => EnemyVariant.Splitter,
_ => EnemyVariant.Wanderer,
});Slot 1 becomes a Hunter only from level 4. Until then the arm is skipped, and the _ arm gives a Wanderer. You first meet is in Chapter 01 and when in Chapter 14. The statement form, case PendingKind.Pop when _stack.Count > 0:, appears in Chapter 17.
Lifetime
Lazy initialisation
Lazy<T> wraps a value that is not built until the first time you ask for it. You read it through .Value. The factory function runs once, and every later read returns the same object.
csharp
private readonly Lazy<GameServices> _services;
...
_services = new Lazy<GameServices>(() => new GameServices(
_config,
GraphicsDevice,
...));The host cannot build GameServices in its constructor, because the graphics device does not exist until LoadContent. Wrapping the construction in Lazy<T> postpones it until then. The services are built together in one step, so there is never a half-built set. The lambda is a closure over the host's fields.
You first meet it in Chapter 05.
IDisposable and using
Some objects hold something the garbage collector cannot free, such as graphics memory or a file handle. A type that holds one implements IDisposable, which has one method, Dispose. Call Dispose when you have finished, and the resource is released at once.
csharp
public void Dispose()
{
_cache?.Dispose();
_cacheSpriteBatch.Dispose();
}A using statement calls Dispose for you, even if an exception is thrown. For example, using var stream = File.OpenRead(path); disposes stream when the enclosing block ends. The course does not use using in its own code. Its owners release resources by hand, in the Dispose of the host and of GameServices.
You first meet Dispose in Chapter 02, and the IDisposable interface in Chapter 05.
Tests
Fact tests
A test is a method that checks one promise. In xUnit, the test library the course uses, you mark it with [Fact]. The runner calls it once. It passes unless an Assert fails or an exception is thrown.
csharp
[Fact]
public void MenuList_WrapsAtBothEnds()
{
MenuList menu = new(["A", "B", "C"]);
Assert.Equal(MenuInput.Moved, menu.HandleInput(Up));
Assert.Equal(2, menu.SelectedIndex);
}The name says what the test proves. The body has three parts: set up the object, do the thing, then assert the result. You first write a [Fact] in Chapter 01.
Theory and InlineData
A [Theory] is a test that runs more than once with different inputs. Each [InlineData] line is one case. Its values are passed to the method as arguments, in order.
csharp
[Theory]
[InlineData(DifficultyPreset.Chill, 4)]
[InlineData(DifficultyPreset.Classic, 3)]
[InlineData(DifficultyPreset.Hardcore, 2)]
public void GetStartingLives_DependsOnDifficulty(DifficultyPreset difficulty, int expectedLives)The runner reports one pass for each case. This theory adds 3 to the test count, not 1. If one case fails, the report names that case, so you know which input is wrong.
When you use dotnet test --filter with a theory name, it runs every case of that theory. Expect Passed to equal the number of [InlineData] rows. You first meet theories in Chapter 14.
Where to read more
This page covers only what the course uses. The official C# documentation explains each feature in full: C# documentation on learn.microsoft.com.

