Programming in Unity · Module 01

C# Fundamentals

From "what is a program", all the way to classes, collections and exceptions. A complete first pass through the C# language to build the foundation you'll carry into Unity.

 

What Is Programming?

Section 01

What a program is, and what a programming language does

Gustave Doré engraving — divine creative power bringing order out of chaos
Him the Almighty PowerGustave Doré

What Is Programming?

Algorithm

ˈæl.ɡə.rɪ.ðəm

1A finite, well-defined sequence of instructions that takes one or more inputs and produces one or more outputs.

e.g.Binary search: given a sorted list, repeatedly halve the search space until the target is found or ruled out.

What Is Programming?

Algorithms Are Everywhere

A cake recipe as an everyday algorithm
  • An algorithm exists independently of any language or machine. It's any defined procedure that turns a clear input into a clear output, whether written in code or followed by hand.
  • Quicksort, Dijkstra's pathfinding, and a cake recipe all qualify. Each takes something in, and produces something out, by following a fixed set of steps.

What Is Programming?

Program

ˈproʊ.ɡræm

1A set of instructions, written in a programming language, that a computer can execute to perform a task.

e.g.A calculator app, a web browser, or a video game.

What Is Programming?

From Algorithm to Code

  • A program is a complete set of instructions, written in a language a computer can actually run. In this course, that language will be C#.
  • An algorithm is just the idea; a program makes it real, tied to a specific language and platform.
  • Programs put algorithms to work, but they do much more: reacting to input, moving data around, drawing to the screen. Much of programming is about wiring these pieces together.
A C# program: an algorithm expressed as runnable code

What Is Programming?

Programming Language

1A formal language with strict, unambiguous rules for writing instructions that can be translated into something a computer executes.

e.g.C#: a general purpose language, used for videogames, desktop apps, enterprise software, and web services.

What Is Programming?

The Right Tool for the Job

No language is the best at everything. Each was built for certain problems, and tends to do that job better than the rest:

  • Python — highly readable, popular for scripting, data analysis, and machine learning.
  • JavaScript — runs in every web browser, but it can also power servers via Node.js.
  • C — manual memory management and good performance.
  • Java — object-oriented, used for enterprise software and Android apps.

They differ in syntax and purpose, but share the same core ideas you are learning now.

 

Introduction to C#

Section 02

Meet the language: History & Characteristics

Gustave Doré drawing of a gnarled monster
Gnarled MonsterGustave Doré

Introduction to C#

What Is C#?

C# (pronounced "see-sharp") is a modern, general-purpose programming language created by Microsoft, first released in 2002. It was designed to be powerful and approachable at the same time, and it has grown into one of the most widely used languages in the world.

It was created by Anders Hejlsberg, who drew on the lessons of C, C++ and Java to keep the parts that worked and smooth over the parts that didn't.

C# code runs on .NET, Microsoft's development platform, which provides the runtime that executes your code and a vast library of ready-made tools.

TIOBE Index

Programming popularity · 2026

Python22.6%
C11.0%
Java8.7%
C++8.7%
C#7.4%
▲ Language of the Year 2025

TIOBE Index

Introduction to C#

What Makes C# Different

  • Statically typed — every variable has a fixed type, checked at compile time, so many mistakes are caught before the program ever runs.
  • Strongly typed — the language won't silently convert between incompatible types behind your back, so the code does what it says.
  • Memory-managed — a garbage collector frees unused memory for you, removing a whole category of crashes you'd hit in a language like C.
  • Object-oriented, but flexible — organised around classes and objects, with strong functional and procedural support when you want it.
  • Batteries included — a huge standard library covers collections, files, networking and more, out of the box.

Introduction to C#

A Word on Syntax

Syntax is the set of rules that define how the symbols of a language may be arranged to form valid constructs. Every language has a syntax; C# is no exception, and its compiler checks your code against C#'s syntax rules. Code that violates them is malformed, so the compiler reports an error and refuses to build the program. Two rules are worth knowing before you write any code:

  • C# is case-sensitive. Capitalisation is part of a name: playerHealth, PlayerHealth and playerhealth are three different things, and Console is not console. A surprising number of beginner errors are just a mistyped capital.
  • Whitespace is for humans. Extra spaces, blank lines, comments, and indentation, are ignored by the compiler, we use them only to keep code readable.

C# belongs to the C family, so its punctuation will look familiar if you've seen C, C++ or Java. We'll meet it properly once we've written our first program.

Introduction to C#

Where C# Is Used

C# reaches far beyond games. The same language and skills carry across:

  • Games — the scripting language of Unity, one of the most popular engines in the world.
  • Desktop apps — Windows software through WPF and WinForms.
  • Web services — back-end APIs and websites with ASP.NET.
  • Mobile & cross-platform — apps for many devices from one codebase with .NET MAUI.

Introduction to C#

Why C# for Game Development

Games are demanding: they have to run in real time, frame after frame, while staying easy enough to change as ideas evolve. C# hits that sweet spot.

  • Performant enough for real-time gameplay, without the memory related bugs that haunt lower-level languages like C or C++.
  • Fast to iterate, so you try an idea, see it running, tweak it, and repeat.
  • Well-supported, with a huge ecosystem of libraries, tools, and community knowledge.

Which is exactly why Unity, the engine we'll use, chose C# as its scripting language.

Introduction to C#

Computers Don't Understand C#

Deep down, a computer's processor understands only one thing: machine code, composed by long strings of 0s and 1s. It cannot read C#. And if you saw machine code yourself, you couldn't read it either.

So there's a gap. You write in C#; the processor speaks only machine code. Something has to translate between the two, like two people who share no language needing an interpreter.

Machine code: long strings of 0s and 1s

Introduction to C#

From Source to CPU

flowchart TD
  A([C# source]) -->|compile| B["CIL — intermediate code"]
  B -->|JIT compile| C["native machine code"]
  C --> D([CPU runs it])

Your code changes form twice before the processor can run it:

  • C# source — the code you write, saved in a .cs file.
  • CIL (Common Intermediate Language) — a compiler translates your C# into this intermediate, "halfway" code, ahead of time. It's no longer C#, but it isn't machine code yet either.
  • Machine code — when you actually run the program, the runtime (using its JIT compiler) turns that CIL into the native instructions your CPU executes.

So there are two translations: C# → CIL ahead of time, and CIL → machine code while the program runs.

Introduction to C#

Why Translate Twice?

Stopping at a "halfway" code instead of going straight to machine code looks like extra work, but it buys two big things:

  • It runs anywhere. The halfway code (CIL) is identical on Windows, Mac, and Linux. Each computer only has to handle the final step its own way, so the very same program runs everywhere without rewriting.
  • It runs fast. That final step happens on your actual machine, right when the code is needed, so the result is tuned to your exact computer.

Introduction to C#

Runtime

ˈrʌn.taɪm

1A program whose job is to run other programs.

e.g.The .NET runtime (Common Language Runtime or CLR) is the one that runs your compiled C#. Java has its own, the JVM, and Mono is another runtime that also runs C#, used by Unity.

Introduction to C#

Terminology

Compiler

The translator: it turns the C# you wrote into CIL (the halfway code) ahead of time.

CIL — Common Intermediate Language

The halfway code itself: not C#, not machine code, but something in between.

CLR — Common Language Runtime

The program that runs your compiled code and manages memory, so you don't have to.

JIT Compiler — Just In Time Compiler

The part of the runtime that does the final translation "just in time", right when each piece of code is first needed.

Introduction to C#

Mono, IL2CPP, and CoreCLR

Unity has to turn the C# you write into something each device can actually run. Over the years it has done this in a few different ways, and you'll hear all three names.

Mono is another version of that .NET runtime, its own independent take on the same idea. Not the CLR itself, but a sibling that does the equivalent job. It was Unity's runtime for years, and a big reason C# could power games across so many platforms. With Mono, the halfway code (CIL) ships inside your game, and the runtime translates it into machine code on the device while the game runs.

IL2CPP ("Intermediate Language to C++") is the newer approach. Instead of translating on the device as it runs, it takes your compiled code and converts it into C++ ahead of time, which is then built into native machine code for each platform. Some platforms, like iOS, don't allow on-the-device translation at all, so IL2CPP became the way to reach them. It also tends to run faster, which is why many modern games use it.

CoreCLR is the modern, cross-platform runtime from today's mainstream .NET (.NET Core and .NET 5 and up). It's the same lineage as the original CLR, but rebuilt to run on Windows, Mac, and Linux, and it's where Microsoft's active development is currently focused. Unity has been working to adopt CoreCLR to replace the aging Mono backend, bringing modern .NET and a much better JIT and garbage collector to the engine, so it's the direction things are heading.

 

Setting up the environment

Section 03

The SDK, an editor, and your first running project

Gustave Doré engraving of a magnificent castle — the structure you set up to build in
Magnificent CastleGustave Doré

Setting Up the Environment

What You Need

To write C#, you need two things, although in practice they often come together:

  • The .NET SDK — the Software Development Kit. It holds the compiler that turns your C# into CIL, the runtime that runs it, and the standard library. Nothing builds or runs without it.
  • A text editor or an IDE — where you write. A good one understands C#, flags mistakes as you type, and runs your program at the press of a button.

The good news: most editors bring the SDK along with them, so installing one often gets you both. The next slides cover the three you'll meet most.

Setting Up the Environment

Your Three Options

Visual Studio

Microsoft's full IDE. Heaviest, but also the most complete, with the SDK bundled in. The free Community edition is the most hand-holding start.

Windows · free (Community)

VS Code

A lightweight, cross-platform editor. Add the C# Dev Kit extension for full C# support; the .NET SDK installs separately. Leaner, a little more setup.

Win / Mac / Linux · free

JetBrains Rider

JetBrains' polished C# IDE, with a bundled SDK and first-class, officially-supported Unity tooling. Free for non-commercial use.

Win / Mac / Linux · free (non-commercial)

All three compile and run your C# the same way, and all three are free while you're learning. On Windows, Visual Studio is the editor Unity installs by default. VS Code is the lighter, cross-platform option. Rider is JetBrains' full IDE, free for non-commercial use.

Setting Up the Environment

Your First Project

> dotnet new console
> dotnet run

Hello, World!

Once your editor and SDK are installed, these two commands prove everything works. Run them in an empty folder from a terminal. See the greeting printed back? Your environment is ready, and you've run your first C# program.

 

Hello, World!

Section 04

Your first program

Gustave Doré engraving of jugglers and acrobats — a first joyful performance for the world
Jugglers and Acrobats at the CastleGustave Doré

Hello, World!

Your First Program

You've already run this. Now, let's look at what you did. When dotnet new console created your project, it didn't leave it blank: it wrote a single line of code for you.

That line is the traditional "Hello, World!". It's the first program you learn how to write when learning a new language.

Console.WriteLine("Hello, World!");
Hello, World!

Hello, World!

Reading the Line

Console.WriteLine("Hello, World!");

Don't worry about the terms below yet: class, method, and operator each get their own section later.

This whole line is one single statement, a single instruction the program runs. Its pieces:

  • Console — the class for the terminal, where text is written and read.
  • . — an operator that reaches into Console.
  • WriteLine — a method that writes a line of text.
  • () — an operator which calls the method.
  • "Hello, World!" — a string indicating the text to show.
  • ; — the statement terminator, ending the statement.

Hello, World!

Wait, That's the Whole Program?

Console.WriteLine("Hello, World!");

If you have ever used another object-oriented language, you would expect for that line to live inside a class and a Main method, like this:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello, World!");
    }
}

When you write it on its own, it's called a top-level statement. C# lets you skip the wrapper and just write code directly.

Hello, World!

Comments

A comment is text the compiler ignores completely. It's there for programmers, to explain why code does something or to leave a note for later. You'll spot them throughout the code examples from here on.

// A single-line comment runs to the end of the line
Console.WriteLine("Hi");   // It can also sit after code

/* A block comment
   can span several lines */

Use comments to explain intent, not to restate the obvious. Clear code with good names usually needs few of them.

Hello, World!

Statements and Blocks

Two structural rules shape every C# program, and you just met both in "Hello, World!":

  • A statement is a single instruction. It ends with a semicolon ;. That's why every line so far finishes with one.
  • A block is a group of statements wrapped in curly braces { }. Methods, loops, and if clauses all attach a block of code to run.
{
    Console.WriteLine("First");   // A statement
    Console.WriteLine("Second");  // Another statement
}                                 // The block groups them together

 

Variables

Section 05

Named, reusable storage for the data your program works with

Gustave Doré engraving of many large fish — a haul of distinct stored values
Many Large FishGustave Doré

Variables

Variable

ˈvɛə.ri.ə.bəl

1A named storage location, with a fixed type, that holds a value you can read and change while the program is running.

e.g.a player's score (number), their name (text), whether the game is over (true/false).

Variables

Declaration & Initialization

string firstName;             // Declaration
firstName = "Al";             // Initialization

string secondName = "John";   // Declaration & initialization

var thirdName = "Jack";       // var: type inferred (string)

Declaring a variable states its type and name. A variable's type (string, int, bool) fixes what kind of value it can hold and what you can do with it; types will be explained in the next section. Initialising gives the variable its first value, and most of the time you do both in one line.

var lets the compiler infer the type from the value, so you don't write it twice. The variable is still strongly typed, var only saves keystrokes, it doesn't make the type flexible.

Variables

Using a Variable

Once a variable has a value, its name stands in for that value wherever you use it; you can read it, compute with it, and reassign it. The most recent value is always the one that counts.

int score = 10;
Console.WriteLine(score);   // 10

score = score + 5;          // Reassign from its own value
Console.WriteLine(score);   // 15

string name = "Aria";
Console.WriteLine($"{name} has {score} points");
10
15
Aria has 15 points

Variables

Locking a Value — const & readonly

const

A true constant, fixed at compile time. Must be set right where it is declared.

const int MaxPlayers = 4;

readonly

Set once at runtime rather than compile time, then frozen. Use it when the value isn't known until the program runs. There's more to readonly than fits here, so we'll explore it properly later in the course.

readonly DateTime startedAt = DateTime.Now;

Variables

Default Values

A field you never assign isn't left as random memory. C# starts it at a default value decided by its type, so every field begins in a known, safe state. Each type's default:

Numbers — int, double, float

0

bool

false

char

'\0'

Reference types (classes, arrays, strings)

null

Locals are the exception: they get no default. The compiler makes you assign a value before first use.

Variables

Naming Variables

A variable's name is for humans first; choose one that says what it holds. Descriptive names make code read like an explanation of itself, vague ones force the reader to guess.

Clear

playerHealth
enemyCount
isGameOver

Vague

x
temp
data

Beyond clarity, C# follows naming conventions: local variables use camelCase (lowercase first word, capitalize each word after), while constants and other members use PascalCase (capitalize each word). A name cannot start with a digit or be a C# keyword.

Variables

Reading Input

Console.Write("What is your name? ");
string name = Console.ReadLine();

Console.WriteLine($"Hello, {name}!");

Programs get more interesting when they react to the user. Console.ReadLine() waits for the user to type a line and press Enter, then hands back what they typed as a string.

Store that string in a variable and you can use it like any other value. Console.Write (no "Line") prints the prompt without moving to a new line, so the answer sits right after it.

Input always arrives as text. Turning it into a number takes a small conversion step. It will be explained later alongside types and operators.

 

Types

Section 06

How C# classifies every piece of data

Gustave Doré engraving of Brother Bruin the bear
Brother BruinGustave Doré

Types

Type

taɪp

1A classification that specifies what kind of data a value is, what it can hold, and which operations are legal on it.

e.g.5 is an integer, "hello" is a string, true is a boolean.

Types

The Benefits of Static Typing

C# is statically typed: it verifies every type at compile time, before the program runs, instead of discovering mismatches at runtime (mid-execution).

Moving this check to the compilation phase gives you four major advantages:

  • Find errors immediately: If you try to do an operation on incompatible data, like strings and integers, the code will not compile, so a whole class of bugs never ships.
  • Faster execution: the data types are already locked in, the runtime doesn't have to waste time looking up what the data is while the program is running.
  • Predictable memory layout: each type has a known size and structure. The runtime can lay out and allocate memory for your data precisely, rather than determining it at runtime.
  • Better coding tools: your code editor knows your data types ahead of time, so it can display highly accurate autocomplete.

Types

Two Families of Type

The two main types in C# are value type (the variable holds the data itself) and reference type (the variable holds an address pointing to data that lives elsewhere). That single split shapes how data is copied, compared and stored. Language specification.

flowchart TD
    T["Types"] --> V["Value type"]
    T --> R["Reference type"]
    T --> TM["[...]"]

    V --> ST["struct"]
    V --> E["enum"]

    R --> C["class"]
    R --> I["interface"]
    R --> A["array"]
    R --> D["delegate"]
    R --> RM["[...]"]

Types

Copy vs Share

Assigning a value type copies the data; the two variables are now independent. Assigning a reference type copies the address, so both names point at the same object.

Value type (copied)

int a = 10;
int b = a;   // b gets a copy
b = 99;      // a is untouched
// a is still 10

Reference type (shared)

int[] x = { 1, 2, 3 };
int[] y = x;   // Same array
y[0] = 99;
// x[0] is now 99 too

Types

Why it is important

This one idea defines everyday behaviour:

  • Whether changing one variable affects another.
  • What a function can and can't change when you pass data into it.
  • How equality and copying behave.

It comes down to one distinction: value types hold the data, reference types point to it. Hold onto that, because many behaviours in C# trace back to which side of the line a type sits on.

Types

Simple Types

C# bakes in a handful of simple types for the most basic kinds of data: whole numbers, decimals, single characters and true/false values. Each one comes with a convenient keyword name. Under the hood, every keyword is just a friendly alias for a type in the .NET library: int is really System.Int32.

int health = 100;
double speed = 5.5;
char grade = 'A';
bool isAlive = true;

Types

"Primitive" — a Word to Use Carefully

People often call these "primitive types", borrowing the term from languages like Java. In C# that word is not quite accurate.

C# has no formal category called "primitive". Its simple types are really structs, full value types with methods of their own. You can write 5.ToString() or int.MaxValue; a true primitive could not do that. So "simple type" is the correct term.

Types

The Four Main Numeric Types

Picking a number type is a trade between range (how big) and precision (how exact).

int

32-bit. No suffix. Whole numbers (scores, indices).

float

32-bit. Suffix f. Inexact. Operations where rounding errors are fine.

double

64-bit. No suffix. Default for decimal literals. Still inexact, but far more headroom. Precise math.

decimal

128-bit. Suffix m. Base-10, exact for decimal values. Money (no rounding errors).

Types

Suffixes Decide the Type

A bare decimal literal is a double. A bare whole number is an int. The suffix tells the compiler you meant something else (float or decimal).

int lives = 3;            // integer by default
float gravity = -9.81f;   // f, without it, 9.81 is a double
double pi = 3.14159;      // double by default
decimal price = 19.99m;   // m, exact, for currency

float gravity = -9.81;    // ERROR: cannot assign double to float
decimal price = 19.99;    // ERROR: cannot convert double to decimal

Integer division truncates (7 / 2 is 3), so promote to a decimal type when you need the fraction: 7 / 2.0 is 3.5.

Types

bool

buːl

1A value type that can hold only one of two values: true or false.

e.g.A bool named isGameOver is false while the player is alive and becomes true when they lose.

Types

true and false

A bool has exactly two possible values: true and false. They usually come from a comparison, and they drive conditionals and loops.

bool isAlive = true;
bool hasKey = false;
bool canEnter = health > 0;   // a comparison produces a bool
if (isAlive)
{
    Console.WriteLine("Keep playing");
}

Types

char

tʃɑːr

1A value type that holds exactly one character, written between single quotes.

e.g.'A', '7', '?' and ' ' (a space).

Types

Character Literals and Encoding

A char holds a single character. It is the building block strings are made of. Its literal (the notation) uses single quotes ('A'), while a string uses double quotes ("A"). Do not mix them up.

Under the hood, a char is a 16-bit number representing a Unicode (UTF-16) code unit, so each character maps to a number you can even do arithmetic on.

char letter = 'A';
char digit = '7';
int code = letter;   // 65 — the Unicode value of 'A'

Types

enum

ˈiː.nʌm

1A value type that defines a named set of related constants, making code more readable and less error-prone.

e.g.Direction { North, East, South, West }.

Types

Declaration and Usage

Declare the set of names, then use them by name. Code reads like English, and printing an enum gives you the name.

enum Direction { North, East, South, West }

Direction facing = Direction.North;

Console.WriteLine(facing);
North

Types

Underlying Types

Each enum member is actually a number, by default an int, starting at 0 and counting up. You can set the values explicitly, or change the underlying type.

enum Difficulty : byte
{
    Easy = 1,
    Normal = 2,
    Hard = 4
}

Here, for example, the underlying type is changed to byte, and each name has a custom value.

Types

The Flags Attribute

[Flags] marks an enum as a bit field, so combined values print as a list of member names, instead of a bare number. Assign each member a distinct power of two so the bits combine cleanly.

[Flags]
enum Toppings
{
    None     = 0,
    Cheese   = 1,
    Bacon    = 2,
    Mushroom = 4
}

Toppings order = Toppings.Cheese | Toppings.Bacon;
Console.WriteLine(order); // "Cheese, Bacon"  (without [Flags]: "3")

The symbol "|" is the bitwise OR operator. It, and the rest of C#'s operators, are explained in the next section.

Types

string

A string is a sequence of characters: names, dialogue, file paths, anything textual. It's written in double quotes like this: "Roma".

Unlike the numeric and char types, string is a reference type: the variable holds a reference to the text, which lives elsewhere in memory. Yet, it behaves like a simple value, because strings are immutable: once created they never change, so you can share one freely without fear that something will change it.

Types

Building Strings

Join strings with + (concatenation), or use string interpolation with $ to drop values straight into the text (far cleaner than a chain of +).

string name = "Aria";
string greeting = "Hello, " + name;            // Concatenation
string line = $"{name} scored {1500 + 250} points";  // Interpolation

Inside an interpolated string, any expression put in { } is evaluated and turned into text.

Types

Escapes and Verbatim Strings

Inside double quotes, a backslash starts an escape sequence for characters you can't type directly: \n (new line), \t (tab), \" (a quote), \\ (a literal backslash).

string path = "C:\\Users\\Aria";    // each \\ is one backslash
string verbatim = @"C:\Users\Aria";  // @ : backslashes are literal
string quote = "She said \"hi\"";

A verbatim string (@"...") takes the text exactly as written, escapes and all. Ideal for Windows paths and multi-line text, where escaping every backslash gets tedious.

Types

Immutability

Strings are immutable: once created, their characters never change. Methods that look like they modify a string actually return a new one and leave the original untouched.

string s = "hello";
s.ToUpper();      // Returns "HELLO", but s is still "hello"
s = s.ToUpper();  // Reassign to actually keep the result

This is exactly what lets you pass a string around safely: nobody you share it with can change it on you.

Types

Strings in Memory

Because a string can be any length, its characters live elsewhere in memory and the variable holds a reference to them. Immutability is what makes that safe to share, but it has a cost.

Since every "change" produces a new string, building text by repeatedly concatenating with + in a loop creates a pile of throwaway strings the runtime must later clean up.

Types

Common String Methods

Strings carry a rich toolkit. Each returns a new string or a value, never modifying the original:

  • Length — number of characters; index with s[0] to read one char.
  • ToUpper / ToLower — change case.
  • Trim — remove surrounding whitespace.
  • Substring — extract part of it.
  • Replace, Split, Contains, IndexOf — search and transform.

Equality compares text, not identity: "hi" == "hi" is true, because string customises (overloads) == to compare characters.

Types

Arrays

An array holds a fixed-size, ordered collection of values that all share the same type, like a row of numbered boxes. Once created, its length never changes.

Arrays are reference types: the variable holds a reference to the block of elements, not the elements themselves. Copying an array variable copies the reference, so both names point to the same data.

Types

Declaration and Initialization

An array type is the element type followed by []: int[], string[]. To make one, either ask for a size (slots filled with the type's default), or list the values and let C# count them.

int[] a = new int[5];             // five slots, all 0
int[] b = new int[] { 1, 2, 3 };  // sized from the values
int[] c = { 10, 20, 30 };         // shorthand for the same

new int[5] reserves five slots and fills them with 0 (the default for int). The { ... } form skips new entirely, the length comes from how many values you wrote.

Types

Accessing Elements

Reach an element by its index, written in [] after the variable and counting from 0. The first element is [0] and the last is [Length - 1]. Going out of range throws an exception at run time.

string[] names = { "Aria", "Ben", "Cleo" };
Console.WriteLine(names[0]);       // Aria  (first)
names[2] = "Cara";                 // overwrite Cleo
Console.WriteLine(names.Length);   // 3
Console.WriteLine(names[3]);       // IndexOutOfRangeException

Types

Multidimensional arrays

A multidimensional array (also called a rectangular array) is a single array with two or more dimensions. It uses one set of brackets with commas [,] and is accessed with multiple indices. Every dimension has a fixed length, which is what makes it "rectangular."

int[,] grid = new int[2, 3];   // 2 rows, 3 columns
grid[0, 0] = 5;
grid[1, 2] = 9;

// Initialize with values directly
int[,] board = { { 1, 2 }, { 3, 4 } };

// Read dimensions
int rows = grid.GetLength(0);  // 2
int cols = grid.GetLength(1);  // 3

All elements occupy one contiguous block of memory, making rectangular arrays compact and efficient for evenly shaped data.

Types

Jagged Arrays

A jagged array is an array whose elements are themselves arrays, an "array of arrays." Each element array can be a different length, hence the jagged edge. It uses multiple sets of brackets [][] and is accessed one index at a time.

int[][] jagged = new int[3][];   // 3 rows, lengths set later
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5 };
jagged[2] = new int[] { 6 };

int x = jagged[1][2];   // 5

// Initialize with values directly
int[][] data = {
    new int[] { 1, 2 },
    new int[] { 3, 4, 5 }
};

Because each row is a separate array, rows can vary in length and be built or replaced independently. Jagged arrays are often faster for row-by-row access, while rectangular arrays use memory more compactly.

 

Operators

Section 07

The symbols that combine, compare and transform your values.

Gustave Doré engraving of a fierce charge, forces combining and acting on each other
They Fiercely Charged ForwardGustave Doré

Operators

What an Operator Is

An operator is a symbol that performs an action on one or more values (its operands) and produces a result. For example, 5 + 3 applies the + operator to the operands 5 and 3 to produce 8. Combining operators and operands forms an expression, a fundamental building block of computation.

  • Unary, one operand: -x (negation), !ready (logical NOT).
  • Binary, two operands: a + b (addition), x < y (comparison).
  • Ternary, three operands: cond ? a : b (the conditional operator, of which C# has exactly one).

Just like in math, precedence decides which operator runs first (2 + 2 * 2 is 6, not 8), associativity breaks ties between operators of equal precedence, and ( ) overrides both. The families below appear in roughly the order you will use them.

Operators

Every Operator at a Glance

Arithmetic

+-*/%++--

Comparison

<><=>=

Equality

==!=

Boolean logic

!&&||

Bitwise & shift

~&|^<<>>>>>

Assignment

=+=-=*=/=%=&=|=^=<<=>>=>>>=

Null handling

????=?.?[]x!

Conditional

? :

Member & access

.( )[ ]^..::

Type & convert

(T)isastypeofsizeofnameof

Expression

=>newawaitdefault

Unsafe & special

&*->checkedstackallocdelegate

Operators

Arithmetic Operators

+-*/%

These do basic arithmetic, with one quirk worth knowing. When both operands are integers, division truncates: 7 / 2 is 3, not 3.5. The % (modulo) operator gives the remainder, useful for even/odd checks and "every Nth" logic.

int sum  = 5 + 3;   // 8    addition
int diff = 5 - 3;   // 2    subtraction
int prod = 5 * 3;   // 15   multiplication
int quot = 7 / 2;   // 3    division (truncates)
int rem  = 7 % 2;   // 1    remainder (modulo)
int neg  = -sum;    // -8   unary minus
int pos  = +sum;    // 8    unary plus

Operators

Increment and Decrement

++--

++ adds one to a variable and -- subtracts one: the shorthand for the very common "change by one", and the usual way to step a loop counter.

The bump is applied the moment that piece of the expression is evaluated, not after the whole line.

int score = 0;
score++;        // +1

int x = 5;
int a = x++;    // a = 5, then x becomes 6  (postfix)
int b = ++x;    // x becomes 7, then b = 7  (prefix)

x = 5;
int r = x++ + x;  // 11: x++ is 5, bumps x to 6, 2nd x is 6

Operators

Assignment and Compound Assignment

=+=-=*=/=%=&=|=^=<<=>>=>>>=??=

= stores a value in a variable. The compound forms combine an operation with assignment, updating a variable from its own current value. There is a compound form for nearly every binary operator.

int x = 10;
x += 5;   // x = x + 5  -> 15   (also -= *= /= %=)
x &= 6;   // x = x & 6          (also |= ^=)
x <<= 1;  // x = x << 1         (also >>= >>>=)
name ??= "Guest";  // assign only if name is null  (??=)

Operators

Comparison Operators

<><=>=

These order two values and always produce a bool. They are the source of nearly every condition you write.

bool c = 5 >  3;   // greater than           -> true
bool d = 5 <  3;   // less than              -> false
bool e = 5 >= 5;   // greater than or equal  -> true
bool f = 3 <= 2;   // less than or equal     -> false

Operators

Equality Operators

==!=

C# treats equality as its own family, separate from ordering. == and != also produce a bool.

For simple values this compares the values themselves. For objects it compares identity by default, unless the type customises it, as string does to compare text.

bool a = 5 == 5;   // equal to      -> true
bool b = 5 != 3;   // not equal to  -> true

Operators

Boolean Logical Operators

!&&||

These combine bool values. && (and) is true only if both sides are, || (or) if either is, and ! (not) flips one.

&& and || short-circuit: they stop the moment the answer is certain. The & and | forms (see Bitwise) do the same logic without short-circuiting.

bool canEnter = isLoggedIn && hasPermission;  // both true
bool useCache = fromCache  || canRetry;       // either true
bool isHidden = !isVisible;                   // flip it

Operators

Conditional (Ternary) Operator

? :

? : is C#'s only ternary operator, a compact if/else that produces a value. Read it as condition, then the value if true, then the value if false.

Both branches must produce a compatible type, because the whole expression yields a single value.

string label = score >= 50 ? "Pass" : "Fail";
//             condition    ? if-true : if-false
int    limit = isPremium ? 500 : 100;

Operators

Bitwise and Shift Operators

~&|^<<>>>>>

On whole numbers these work bit-by-bit, used for flags, masks, and low-level work. You will reach for them rarely as a beginner. The &, | and ^ forms double as non-short-circuiting boolean operators.

int and = 0b1100 &  0b1010;   // 0b1000  AND
int or  = 0b1100 |  0b1010;   // 0b1110  OR
int xor = 0b1100 ^  0b1010;   // 0b0110  XOR
int not = ~0b1100;            // flip all bits
int lsh = 1 << 4;             // 16   x * 2^n
int rsh = 32 >> 2;            // 8    x / 2^n
uint ur = 0xF0000000u >>> 4;  // unsigned right shift

Operators

Member Access: the Dot

.?.

The . operator reaches into a value to use its members (fields, properties, and methods), and to qualify names inside namespaces.

Its null-safe sibling ?. only accesses the member if the left side is not null (see Null-Handling).

account.Balance;          // read a property or field
account.Withdraw(10);     // call a method
order.Customer.Name;      // chain: member of a member
System.Console.WriteLine("hi");  // qualify in a namespace

Operators

Invocation and Grouping: Parentheses

( )

As the invocation operator, parentheses call a method or delegate, passing arguments. As grouping, they override precedence, forcing part of an expression to run first.

Casts (int)x and tuples (1, 2) reuse parentheses too, but those are separate features.

Greet("Aria");        // invocation: call with one arg
int n = Square(5);    // call, then use the result

int a = 2 + 3 * 4;    // 14: * runs before +
int b = (2 + 3) * 4;  // 20: grouping forces + first

Operators

Element Access: Square Brackets

[ ]?[]^..

The [ ] operator reads or writes an element by position or key, across arrays, lists, dictionaries, and any type with an indexer.

The null-safe ?[] only indexes if the value is not null. The index-from-end ^ and range .. operators are used inside [ ].

int first = scores[0];      // zero-based
scores[0] = 99;             // also assigns
int qty = prices["apple"];  // dictionary: by key
char c  = name[^1];         // ^  last element (from end)
int[] slice = scores[1..3]; // .. a range (sub-array)

Operators

Null-Handling Operators

????=?.?[]x!

These make working with values that might be null both safe and concise.

?., ?[] and ?? short-circuit: if the left side is null, the rest is not evaluated.

int len = name?.Length ?? 0;  // ?. then ?? : 0 if null
int first = list?[0] ?? -1;   // ?[] index if not null
name ??= "Guest";             // ??= assign if null
string s = maybeNull!;        // ! trust: not null

Operators

Type-Testing and Cast Operators

isas(T)typeofsizeofnameof

These inspect or change a value's type. Casting itself gets a fuller treatment just ahead.

is also powers pattern matching: if (o is string s) tests and names the value in one step.

object o = "hi";
bool   isStr = o is string;   // is      type test
string str   = o as string;   // as      or null
int    n     = (int)9.8;      // (T)x    cast -> 9
Type   t     = typeof(int);   // typeof  the Type
string nm    = nameof(count); // nameof  "count"
int    sz    = sizeof(int);   // sizeof  4 bytes

Type Conversion

Implicit vs Explicit Conversion

Implicit: widening

When there is no risk of losing data, C# converts automatically. A smaller type widens into a larger one, the way an int fits perfectly inside a double.

int whole = 7;
double precise = whole;  // 7 -> 7.0 auto

Explicit: narrowing

When a conversion might lose data, C# refuses to do it silently. You must cast with (type) in front of the value, accepting the risk.

double precise = 9.8;
int whole = (int)precise;  // 9, dropped

Casting between number types truncates rather than rounding, so (int)9.8 is 9, not 10.

Type Conversion

Conversion Methods

Casts move between related numeric types, but turning text into numbers (and back) calls for library methods instead.

  • Parse throws a FormatException on invalid text.
  • TryParse reports success as a bool and writes the result through out; prefer it for user input.
  • ToString renders almost any value as text.
int n = int.Parse("42");          // string -> int (throws)
bool ok = int.TryParse("42", out n);  // safe: false on bad
string s = 42.ToString();         // int -> string
double d = Convert.ToDouble("3.14");  // many target types

Operators

Lambda and Other Operators

=>newawaitdefault::

A grab-bag of operators that each build a specific kind of expression. new creates an object, and :: qualifies a name through a namespace alias.

switch and with read like these but are expressions, not operators, so they are not listed here.

var list = new List<int>();   // new    create an object
numbers.Where(x => x > 0);    // =>     lambda
await LoadAsync();            // await  async result
int d = default;              // default value (0)
var con = global::System.Console.Out;  // :: alias

Operators

Rarely-Used and Unsafe Operators

&*->checkedstackallocdelegate

You will likely never write these in everyday code, but they complete the set.

  • checked / unchecked: turn integer overflow checking on or off for an expression.
  • delegate: the older anonymous-method form, mostly replaced by lambdas (=>).
  • stackalloc: allocate a small array on the stack, as in stackalloc int[8].
  • true / false: a type can define these so its values work directly in if and &&.
  • & (address-of), * (indirection), -> (pointer member): pointers, only inside an unsafe block.

Operators

Operators vs Punctuators

( )[ ].{ }

Some symbols look like operators but are really punctuators: they shape code rather than compute a value.

  • Operators: ( ) invocation and grouping, [ ] element access, and . member access. These act on operands and yield a value.
  • Punctuators: { } blocks and initialisers, ; end of statement, , separator, : labels and the second half of ? :, and the $"…" / @"…" string prefixes. These are structure, not operators.

So ( ), [ ] and . are operators, while { } is not.

Operators

Strong vs Weak Typing

Languages differ in how strictly they enforce types, and that shapes how many mistakes the compiler can catch for you. In a strongly typed language, types are enforced: you cannot accidentally treat text as a number. In a weakly typed language, types bend silently, which is flexible but error-prone.

There is a separate axis. Static typing checks types at compile time, while dynamic typing checks them at run time. C# sits firmly on the strict side of both: it is strongly and statically typed.

Operators

C# vs JavaScript

C#: strong and static

An illegal mix is rejected before the program ever runs, so the bug is caught at compile time instead of at run time.

int x = 5;
x = "hello";      // type error
int n = 5 + "3";  // error: no coercion

JavaScript: weak and dynamic

The same code runs, but types bend silently. + quietly turns the number into text, and the mistake surfaces much later.

let x = 5;
x = "hello";      // fine, now a string
let n = 5 + "3";  // "53": coerced to text
let m = 5 * "3";  // 15: coerced to number

Neither result is "wrong" in JavaScript; its rules simply let unrelated types mix. C# trades that flexibility for catching the error up front.

Operators

Why It Matters

  • Fewer runtime surprises: many bugs become compile errors.
  • Better tooling: autocomplete and refactoring rely on known types.
  • A little more typing up front: you state your types, but gain safety in return.

Catching a type error at compile time is far cheaper than discovering it once the program is already running.

 

Conditionals

Section 08

Letting your program decide

Gustave Doré engraving of a forking road to perdition — choosing one branch over another
The Road to PerditionGustave Doré

Conditionals

Conditionals

A conditional runs code only when a certain condition is true.

Every conditional is driven by a boolean expression that evaluates to true or false. C# gives you a few branching tools, each suited to a different shape of decision:

  • if / else if / else: the general-purpose branch: run one block out of several.
  • The ternary ? :, a compact if/else that produces a value.
  • switch statement & expression: clean branching when one value is tested against many options.

Conditionals

if

The if is the simplest branch. On its own, it does one thing:

  • It tests the boolean condition inside the round parentheses.
  • If that condition is true, the statement runs.
  • If it's false, the statement is skipped and execution carries on below.

There's no fallback here, a lone if either runs its statement or does nothing.

int score = 60;

if (score >= 50)
{
    Console.WriteLine("You passed!");
}

Console.WriteLine("Done.");
You passed!
Done.

Conditionals

else

int score = 40;

if (score >= 50)
{
    Console.WriteLine("You passed!");
}
else
{
    Console.WriteLine("Try again.");
}
Try again.

An if often needs a fallback. That's what else provides:

  • else is optional and attaches to an if.
  • It runs only when the if's condition was false.
  • Exactly one of the two blocks always runs, never both, never neither.

Conditionals

else if

To choose between more than two outcomes, you can chain extra tests with else if:

  • Each else if adds another condition, checked only if the ones above it failed.
  • The final else is a catch-all when nothing matches.
int score = 35;

if (score >= 90)
{
    Console.WriteLine("Gold");
}
else if (score >= 50)
{
    Console.WriteLine("Silver");
}
else
{
    Console.WriteLine("Bronze");
}
Bronze

Conditionals

Reading a Flow Diagram

flowchart TD
  A([Start]) --> B{"score >= 90 ?"}
  B -->|true| C["print Gold"]
  B -->|false| D{"score >= 50 ?"}
  D -->|true| E["print Silver"]
  D -->|false| F["print Bronze"]
  C --> Z([Done])
  E --> Z
  F --> Z

A flow diagram shows the route a program takes as it runs. You start at the top and follow the arrows. Diamonds are decision points, each one has two arrows out, labelled true and false. Rectangles are actions.

  • If the first check returns true, gold is printed, and the program ends.
  • If the result is false, it sends you down to the next check.
  • If the second check succeeds, it prints Silver, otherwise, it prints Bronze.

Because the first match skips the rest, order matters: always try to put the highest-priority conditions first. Every path ends at Done.

Conditionals

Nested Conditionals

Since the if has a block of instructions, you can put another if inside that block. The inner one is reached only if the outer one holds, so both conditions must be true to reach the innermost block.

if (isLoggedIn)
{
    if (hasPermission)
    {
        OpenEditor();
    }
}

Useful, but deep nesting quickly gets hard to read. You can often flatten it, combine the tests with &&, or return early. Keep nesting shallow.

flowchart TD
  A([Start]) --> B{"isLoggedIn ?"}
  B -->|no| E([Done])
  B -->|yes| C{"hasPermission ?"}
  C -->|no| E
  C -->|yes| D["OpenEditor()"]
  D --> E

Conditionals

The Conditional (Ternary) Operator

The ternary operator ? : is a compact if/else that produces a value rather than executing a statement. It's written as "condition ? value if true : value if false"

The distinction in one line: a ternary returns a value, an if performs an action.

  • Use ? : when choosing between two values for one variable or argument.
  • Use a full if when a branch does something: multiple statements, side effects, or more than two outcomes.
int health = 30;
string status = health > 0 ? "Alive" : "Dead";   // "Alive"

// The long way, as if/else:
string label;
if (health > 0) label = "Alive";
else label = "Dead";

Conditionals

switch Statement

When you're comparing one value against many fixed options, a switch is cleaner than a long if / else if chain. Each case labels a value to match, break ends that case, and default catches anything left over.

Unlike C and C++, C# does not let one case silently fall through into the next. Each case must end (usually with break), so a case can't be skipped by accident.

switch (direction)
{
    case 'N':
        Console.WriteLine("Moved North");
        break;
    case 'S':
        Console.WriteLine("Moved South");
        break;
    case 'E':
        Console.WriteLine("Moved East");
        break;
    default:
        Console.WriteLine("Unknown");
        break;
}

Conditionals

How a switch Branches

flowchart TD
  A([direction]) --> B{"match?"}
  B -->|"N"| C["print Moved North"]
  B -->|"S"| D[" print Moved South"]
  B -->|"E"| E["print Moved East"]
  B -->|else| F["print Unknown"]
  C --> G([Done])
  D --> G
  E --> G
  F --> G

A switch evaluates the value once, then jumps straight to the matching case. It doesn't walk through a series of separate conditions the way an if chain does.

  • Each case is a single fixed value to match.
  • default is the catch-all, the switch equivalent of a final else.
  • Exactly one path runs, then execution continues after the closing brace.

Conditionals

switch vs if / else if

if / else if chain

if (direction == 'N')
  {
      Move(1);
  }
  else if (direction == 'S')
  {
      Move(-1);
  }
  else
  {
      Console.WriteLine("Unknown");
  }

switch

switch (direction)
  {
      case 'N':
          Move(1);
          break;
      case 'S':
          Move(-1);
          break;
      default:
          Console.WriteLine("Unknown");
          break;
  }

Both express the same logic. The if chain re-states the variable in every test, so it's the better fit when conditions genuinely differ (ranges, several variables, complex boolean logic). The switch names the value once and lists the options, staying readable as cases multiply, ideal when matching one value against many constants.

Conditionals

switch Expression

A more advanced, modern form: the switch expression. Where the switch statement runs code, a switch expression evaluates to a value, using => arms and _ as the catch-all.

string label = score switch
{
    >= 90 => "Gold",
    >= 50 => "Silver",
    _     => "Try again"
};

This belongs to C#'s functional programming features, the same family as lambdas and LINQ, which favour expressions that produce values over statements that perform actions. It also pairs naturally with pattern matching (testing types, shapes and ranges, not just equality). We look at pattern matching next.

Conditionals

Pattern Matching

You have already used patterns without naming them: the >= 90 arms of the switch expression and the is operator both test a value’s shape, not just whether it equals something.

That is pattern matching: checking a value’s type, range or structure (or whether it is null), then optionally capturing it in the same step — something a plain == check cannot do.

Pattern matching — C# reference

object value = "Aria";</div>
    </div>
    // Type pattern: test the type AND capture it
if (value is string text)
{
    Console.WriteLine(text.Length);   // 4
}

// Type, constant and null patterns in a switch
string kind = value switch
{
    int n    => $"int: {n}",
    string s => $"string: {s}",
    null     => "nothing",
    _        => "other"
};

Conditionals

Combining Patterns

Patterns get expressive when combined, reading almost like English:

  • Relational: < > >= <= test a range, as in >= 90.
  • Logical: and, or, not join patterns, as in >= 0 and <= 100 or not null.
  • Guards: a when clause adds an extra condition to a case, e.g. case > 30 when isSummer:.

That is why a switch can do far more than match constants.

string grade = score switch
{
    < 0 or > 100 => "invalid",    // logical: or
    >= 90        => "A",          // relational
    >= 50        => "pass",
    _            => "fail"
};

Conditionals

List Patterns

Newer C# can also match the shape of a whole array or list. A list pattern puts a sub-pattern in [ ] for each position.

  • .. matches any number of elements.
  • var captures an element into a name.
  • _ matches one element but ignores it.
int[] roll = { 1, 2, 3 };

// Match an exact shape
bool straight = roll is [1, 2, 3];   // true

// Capture pieces;  ..  skips the rest
if (roll is [var first, .., var last])
{
    Console.WriteLine($"{first}..{last}");  // 1..3
}

 

Loops

Section 09

Repeating work without repeating yourself.

Gustave Doré engraving of Munchausen pulling on his own braid — a self-referential repeating act
Pulled on My Own BraidGustave Doré

Loops

Loops

Programs constantly need to repeat work: deal a card to each player, step over every tile on a map, keep updating a game until it ends. A loop does that for you, running a block of code (its body) over and over, each pass called an iteration.

Every loop is driven by a boolean condition, just like an if. The difference: an if runs its block at most once, while a loop keeps re-running it as long as the condition stays true.

  • while — repeat while a condition holds, the most basic form.
  • do-while — the same, but always run the body at least once.
  • for — repeat a known number of times, with its counter built in.
  • foreach — visit every item in a collection, no counter needed.

Loops

while Loop

flowchart TD
  A([Start]) --> R["roll a die"]
  R --> B{"roll != 6 ?"}
  B -->|yes| C["print; roll again"]
  C --> B
  B -->|no| E([Done])

The while loop is the most basic: give it a condition and it repeats its body as long as that condition stays true, checking it before every pass. Reach for it when the repetition count depends on something you cannot predict: user input, randomness, the state of the world.

Random rng = new Random();
int roll = rng.Next(1, 7);     // A random 1-6
while (roll != 6)
{
    Console.WriteLine($"Rolled {roll}");
    roll = rng.Next(1, 7);     // Roll again
}

Every run takes a different number of rolls, there is no count to calculate in advance.

Loops

Infinite Loops

A loop ends only when its condition becomes false. If the body never makes that happen, it forgets to change the variable, or changes it but skips past the target, the loop runs forever: this is an infinite loop, a classic beginner bug.

int n = 0;
while (n != 10)
{
    Console.WriteLine(n);
    n += 3;        // 0,3,6,9,12... never exactly 10
}

Sometimes an endless loop is exactly what you want, a game’s main loop, for instance. In that case, you can write it on purpose with while (true) and step out with break when you are done.

while (true)
{
    string cmd = Console.ReadLine();
    if (cmd == "quit") break;   // The way out
    Console.WriteLine($"You said: {cmd}");
}

Loops

do-while Loop

flowchart TD
  A([Start]) --> B["read input"]
  B --> C{"input != quit ?"}
  C -->|yes| B
  C -->|no| D([Done])

A do-while is a while with one twist: it checks the condition after the body, so the body always runs at least once. Ideal for menus and input prompts, where you must act before you can test.

string input;

do
{
    input = Console.ReadLine();
}
while (input != "quit");

Loops

for Loop

flowchart TD
  A([Start]) --> B["i = 0"]
  B --> C{"i < 5 ?"}
  C -->|yes| D["print i"]
  D --> E["i++"]
  E --> C
  C -->|no| F([Done])

A for loop is a while with its bookkeeping gathered into one header. The diagram shows the three parts it bundles, separated by semicolons:

  • Initializer int i = 0 — runs once, at the start.
  • Condition i < 5 — checked before each pass.
  • Step i++ — runs after each pass.
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);   // 0,1,2,3,4
}

Loops

foreach Loop

flowchart TD
  A([Start]) --> B{"more items ?"}
  B -->|yes| C["item = next"]
  C --> D["print item"]
  D --> B
  B -->|no| E([Done])

The foreach loop walks through every item in a collection (an array, a list) in turn, handing you each one with no index to manage. It is the cleanest way to read a collection.

string[] names = { "Aria", "Ben", "Cleo" };

foreach (string name in names)
{
    Console.WriteLine(name);
}

Reach for for instead when you need the index, or want to replace elements.

Loops

Choosing a Loop

They all repeat, but each answers a different question. Pick by what you know going in:

for

You know the count, or need the index. "Do this 10 times."

while

Repeat while a condition holds, count unknown. "Until the player quits."

do-while

Like while, but run the body at least once. "Show the menu, then ask again."

foreach

Visit every item in a collection. "For each enemy in the wave."

When more than one fits, choose the one that best states your intent.

Loops

Loop Control

By default a loop runs its whole body every pass, then re-checks its condition at the top. Sometimes you need to steer it from the inside: bail out early, or skip the rest of a single pass. Two keywords do that, and both work in every loop (for, while, foreach):

break

Stops the loop entirely and jumps to the code after it. "I am done, no point continuing."

continue

Skips the rest of this pass and jumps straight to the next iteration. "Not this one, on to the next."

Both are almost always guarded by an if, so they fire only in the case you care about. The next two slides show each one in action.

Loop Control

break

flowchart TD
  A([Start]) --> B{"i < 10 ?"}
  B -->|no| F([Done])
  B -->|yes| C{"i == 5 ?"}
  C -->|yes| F
  C -->|no| D["print i"]
  D --> E["i++"]
  E --> B

break exits the loop immediately, skipping any remaining iterations. Great for stopping as soon as you've found what you need.

for (int i = 0; i < 10; i++)
{
    if (i == 5) break;     // Stop the whole loop at 5
    Console.WriteLine(i);  // Prints 0..4
}

Loop Control

continue

flowchart TD
  A([Start]) --> B{"i < 6 ?"}
  B -->|no| G([Done])
  B -->|yes| C{"i is odd ?"}
  C -->|yes| E["i++"]
  C -->|no| D["print i"]
  D --> E
  E --> B

continue skips the rest of the current pass and jumps to the next iteration. Use it to ignore items that don't qualify.

for (int i = 0; i < 6; i++)
{
    if (i % 2 != 0) continue;  // Skips odd numbers
    Console.WriteLine(i);      // Prints 0,2,4
}

Loop Control

Nested Loops

flowchart TD
  A([Start]) --> B{"row < 3 ?"}
  B -->|no| H([Done])
  B -->|yes| C["col = 0"]
  C --> D{"col < 3 ?"}
  D -->|yes| E["print row,col"]
  E --> F["col++"]
  F --> D
  D -->|no| G["row++"]
  G --> B

A loop inside another loop is a nested loop; the inner one runs fully for each pass of the outer. Essential for grids and tables. A break only exits the innermost loop it's currently in.

for (int row = 0; row < 3; row++)
{
    for (int col = 0; col < 3; col++)
    {
        Console.Write($"({row},{col}) ");
    }
    Console.WriteLine();
}

 

Functions

Section 10

Naming and reusing a block of logic, the first big step toward organised code.

Gustave Doré engraving of a parrot urging her on — a named helper called to act
The Parrot Urged Her OnGustave Doré

Functions

Function

ˈfʌŋk.ʃən

1A named, reusable block of code that takes optional inputs, performs a task, and optionally returns a result.

e.g.A Square function takes a number and returns it multiplied by itself.

Functions

Why Functions

So far our programs have been one long run of statements. That works until it does not: the same code is present three times, and a single screen of code becomes hard to follow. Functions fix both, giving blocks of logic a name, which you can write and call wherever you need.

Reuse

Write once, call anywhere (Don't Repeat Yourself).

Readability

A good name like CalculateDamage says what the code does, so the reader grasps it at a glance without tracing through the how.

Decomposition

Break a big problem into small, named steps you can reason about one at a time.

It is the first real tool for taming complexity, and the foundation programming is built upon.

Functions

C# Has No Standalone Functions

Every C# function lives inside a type

Strictly speaking, C# doesn't have free-floating functions. Every function belongs to a type and is called a method. We'll meet methods properly in the OOP section.

For now, top-level statements let us declare local functions and call them as if they were standalone. It's a convenient pretence so we can learn the idea before learning classes.

Functions

Anatomy of a Function

int Add(int a, int b)
{
    return a + b;
}

int sum = Add(3, 4); // 7

Every function declaration is built from the same parts:

  1. Return type int — the kind of value it hands back (void if none).
  2. Name Add — how you call it; pick a verb that says what it does.
  3. Parameters (int a, int b) — the named inputs, in parentheses.
  4. Body — the { } block that runs when it is called.
  5. return — sends a value back and ends the function.

The name and parameter list together form the function's signature, what identifies it (the return type isn't part of it, so two functions can't differ by return type alone). The call Add(3, 4) then runs it and becomes 7.

Functions

Parameters and Arguments

Parameters name the inputs; arguments are the values passed in

Parameters are the named inputs in a function's definition. Arguments are the actual values you pass when you call it.

void Greet(string name)   // 'name' is a parameter
{
    Console.WriteLine($"Hello, {name}");
}

Greet("Aria");   // "Aria" is the argument

Functions

Returning a Value

A function's return type declares the kind of value it hands back. The return keyword sends that value to the caller and ends the function on the spot.

int Add(int a, int b)
{
    return a + b;   // hands an int back to the caller
}

int total = Add(3, 4) + Add(1, 1);   // 7 + 2 = 9

Because the call becomes the value it returns, you can use it anywhere that value fits: store it, print it, or combine it in a bigger expression. Think of a returning function as a question that gives an answer.

Functions

void: Do or Return

Returns a value

Computes an answer you use elsewhere. Its type is the kind of value it gives back.

int Square(int n)
{
    return n * n;
}

int area = Square(5);  // 25

Returns nothing: void

Performs an action (print, move, save) with no value to hand back. Its type is void.

void PrintScore(int score)
{
    Console.WriteLine($"Score: {score}");
}

PrintScore(1500);

Functions

Passing Arguments

The basic call passes values in order: Move(10, 5). But C# offers several ways to make calls clearer and more flexible. The next slides cover each:

  • Named arguments — label each value at the call site.
  • Optional parameters — give a default so callers can omit it.
  • params — accept any number of arguments at once.
  • ref / out — pass the variable itself, not just a copy.

The first three are about calling convenience; ref and out change how the argument is passed.

Functions

Named Arguments

void Move(int x, int y)
{
    // ...
}

Move(10, 5);          // positional — order matters
Move(x: 10, y: 5);    // named, declared order
Move(y: 5, x: 10);    // named, reordered — same result

A named argument labels a value with its parameter's name right at the call site. It makes a call self-documenting — Move(x: 10, y: 5) reads better than a bare Move(10, 5).

You can either keep the parameters' declared order, or list them in a different order — with names, it's the label, not the position, that decides where each value goes.

That reordering is only possible because they're named. Plain positional arguments must follow the parameter order exactly; you can't shuffle them around without giving each one a name.

Functions

Optional Parameters

Give a parameter a default value and callers may leave it out — when they do, the default is used in its place.

Optional parameters must come after all the required ones, so the compiler can tell which arguments you've supplied.

Pair them with named arguments to skip over one optional parameter while still setting another.

void Attack(int damage, bool critical = false)
{
    // critical defaults to false when omitted
}

Attack(10);                 // critical is false
Attack(10, true);           // critical is true
Attack(10, critical: true); // same, but clearer

Functions

The params Keyword

params lets one parameter accept any number of arguments: the compiler gathers them into an array for you, so the caller just lists values instead of building the array first. It's how methods like Console.WriteLine and string.Format take a variable number of inputs.

void Log(string tag, params string[] messages)
{
    foreach (string m in messages)
        Console.WriteLine($"[{tag}] {m}");
}

Log("INFO", "started", "loading", "ready");  // many arguments
Log("WARN", "low memory");                    // just one
Log("DEBUG");                                  // none is still valid

It coexists with ordinary parameters (tag here), but with two rules: a method may have only one params parameter, and it must be the last one. Callers can pass a comma-separated list, a ready-made array, or nothing at all.

Functions

ref and out Parameters

By default an argument is passed by value: the function gets a copy, so changes inside it never reach the caller's variable (the value-vs-reference split from Types). ref and out pass the variable itself, letting the function write back to it.

  • ref — the variable must be initialised before the call. The function may read it and change it.
  • out — the variable need not be set first, but the function must assign it before returning. It's the way to hand back extra results.

The keyword goes on both the parameter and the argument, so the hand-off is visible at the call site.

// ref: change an existing value</div>
    </div>
    void Double(ref int n)
{
    n *= 2;
}

int x = 5;
Double(ref x);   // x is now 10

// out: hand back a second result
bool ok = int.TryParse("42", out int result);
// ok is true, result is 42

Functions

Expression-Bodied Functions

When a function is a single expression, => gives a compact one-line form — no braces, no return keyword.

int Square(int n) => n * n;
string Greet(string name) => $"Hello, {name}";

Identical behaviour to the block form, just tidier for short functions.

Functions

Recursion

flowchart TD
  A["Factorial(4)"] --> B["4 * Factorial(3)"]
  B --> C["3 * Factorial(2)"]
  C --> D["2 * Factorial(1)"]
  D --> E["1 — base case, stop"]

A recursive function is one that calls itself, solving a problem by reducing it to a smaller version of the very same problem.

Every recursive function is built from two parts:

  • A base case — the simplest input, answered directly with no further call. It's what stops the recursion.
  • A recursive case — calls the function again on a smaller input, always moving toward the base case.

Each call pauses, waiting on the one inside it; nothing resolves until the base case is finally reached.

Functions

Recursion — Unwinding the Stack

int Factorial(int n)
{
    if (n <= 1) return 1;        // base case
    return n * Factorial(n - 1); // recursive case
}

Factorial(4);   // 24

Factorial(4) can't finish until it knows Factorial(3), which waits on Factorial(2), and so on. Each unfinished call is stacked up, paused part-way through.

At Factorial(1) the base case returns 1 outright. Now the stack unwinds — each waiting call multiplies and returns in turn: 1 → 2 → 6 → 24.

Forget the base case, or fail to shrink the input toward it, and the calls never stop. The pile of paused calls grows until it runs out of room and the program crashes with a stack overflow — recursion's version of the infinite loop.

 

Scope and Lifetime

Section 11

Where a variable can be seen, and how long it lives.

Gustave Doré engraving of a labyrinth — bounded regions where a name is visible
In Labyrinth of Many a RoundGustave Doré

Scope and Lifetime

Scope and Lifetime

Scope is where in your code a name is visible; lifetime is how long its value exists in memory. The two are closely linked — a variable usually lives exactly as long as the block it's declared in is running.

A name is only usable within the region where it's declared; outside it, the compiler doesn't even know it exists. That's what keeps unrelated parts of a program from stepping on each other's names.

Scope and Lifetime

Local Variables

A local variable is declared inside a function and exists only while that function runs. Each call gets its own fresh copy, and it's gone when the function returns.

void Play()
{
    int score = 0;   // local to Play
    score += 10;
}                    // score ceases to exist here

Scope and Lifetime

Block Scope

A block is any region between { } — a loop body, an if, or a bare pair of braces. A variable declared inside a block is visible only within it.

if (isAlive)
{
    int bonus = 50;   // exists only inside these braces
    score += bonus;
}
// bonus is not accessible here

Scope and Lifetime

Variable Shadowing

Shadowing happens when an inner scope declares a name that already exists in an outer scope. The inner one "hides" the outer for that region. C# forbids it for local variables to prevent confusion.

int value = 10;
{
    int value = 20;   // error in C#: already declared in an enclosing scope
}

It can occur between a field and a local, which is one reason clear names matter.

 

Memory

Section 12

A first look at where your data lives while a program runs.

Gustave Doré engraving of corpse candles — faint lights marking where things still linger
Corpse CandlesGustave Doré

Memory

What Is Memory?

While your program runs, all its data lives in memory (RAM) — picture an enormous wall of numbered lockers, each holding a small piece of data. The CPU fetches and stores values by those numbers, called addresses.

Variables are really just friendly names for locations in that memory. Your code never juggles raw addresses — C# handles that for you.

Memory

The Stack and the Heap

The Stack

Fast, organised, automatic. Holds local variables and tracks which function is running. Grows and shrinks neatly as functions are called and return.

The Heap

A larger, flexible pool for data whose size or lifetime isn't fixed — the objects that reference types point to. Managed by the garbage collector.

This is the overview; we'll revisit both in depth after you've met classes.

Memory

Value and Reference Types in Memory

This is where the value/reference distinction becomes concrete:

  • Value types typically live right on the stack, holding their data inline.
  • Reference types live on the heap; the variable on the stack just holds a reference (address) to them.

That's why copying a value type duplicates the data, while copying a reference type shares it.

Memory

How C# Manages Memory for You

In some languages you must manually free every piece of memory you allocate — and forgetting causes leaks and crashes. C# is managed: the garbage collector automatically reclaims heap objects you're no longer using.

You focus on logic; the runtime handles cleanup. We'll see how the GC works in the deep-dive section.

 

Introduction to OOP

Section 13

A way of organising programs around the "things" in your problem.

Gustave Doré engraving of a courting scene — objects relating to one another
CourtingGustave Doré

Introduction to OOP

Programming Paradigms

A paradigm is a style of organising and thinking about code. Languages tend to favour one or more. Understanding the main paradigms explains why C# is shaped the way it is.

Programming Paradigm

1A fundamental style or approach to structuring programs and reasoning about them.

e.g.Procedural, object-oriented and functional are three of the most influential paradigms.

Programming Paradigms

Procedural Programming

Procedural programming organises code as a sequence of steps and functions that act on data. It's exactly the style we've used so far: do this, then that, calling functions along the way.

Simple and direct, but it can get unwieldy as a program grows and data and behaviour drift apart.

Programming Paradigms

Object-Oriented Programming

Object-oriented programming bundles data and the behaviour that acts on it into objects. Instead of functions floating beside loose data, each object owns its data and the methods that operate on it.

This models real-world "things" — a Player, an Enemy, an Inventory — very naturally.

Programming Paradigms

Functional Programming

Functional programming treats computation as the evaluation of functions, favouring immutable data and avoiding hidden state changes. It leads to predictable, easily testable code.

C# borrows many functional ideas — lambdas, LINQ, immutability — even though it isn't a purely functional language.

Programming Paradigms

How C# Supports Multiple Paradigms

C# is multi-paradigm. It's object-oriented at its core, fully supports procedural code (the top-level statements you've been writing), and embraces functional techniques too.

You can pick the right style for each problem — but OOP is the backbone we'll build on next.

Introduction to OOP

What Is OOP?

Object-oriented programming structures a program as a set of cooperating objects, each combining state (data) with behaviour (methods). It's the dominant way large C# and Unity projects are built.

What Is OOP

The Four Pillars

  • Encapsulation — bundle data with the code that uses it, and hide the internals.
  • Inheritance — build new types on top of existing ones, reusing what they offer.
  • Polymorphism — treat different types through a shared interface, each behaving in its own way.
  • Abstraction — expose the essentials and hide needless detail.

Each pillar gets its own treatment later in the course.

What Is OOP

Why OOP Exists

As programs grow, loose functions and shared data become hard to manage. OOP tames that complexity by:

  • Grouping related data and behaviour so they evolve together.
  • Hiding internals, so changes stay local and safe.
  • Encouraging reuse through inheritance and shared contracts.

What Is OOP

How C# Implements OOP

C# gives you the full OOP toolkit: class and struct to define types, access modifiers for encapsulation, inheritance via :, virtual/override for polymorphism, and abstract classes and interfaces for abstraction.

The next sections introduce each of these in turn.

 

Classes and Objects

Section 14

The blueprint and the thing built from it — the heart of OOP.

Gustave Doré engraving of a giant — one grand blueprint made concrete and towering
A GiantGustave Doré

Classes and Objects

Classes and Objects

This is the cornerstone of OOP. A class is a blueprint that defines what a kind of thing has and does; an object is a concrete instance built from that blueprint.

Classes and Objects

What a Class Is

A class defines a new type by describing its data (fields) and behaviour (methods). It's a template — defining a class doesn't create any actual data yet.

class Player
{
    public string Name;
    public int Health;

    public void TakeDamage(int amount)
    {
        Health -= amount;
    }
}

Classes and Objects

What an Object Is

An object is a real instance of a class, with its own copy of the data, living in memory. From one Player class you can make many independent players.

Player hero = new Player();
hero.Name = "Aria";
hero.Health = 100;
hero.TakeDamage(30);   // hero.Health is now 70

Class vs Object

1A class is the blueprint; an object is a specific thing built from it. One class, many objects.

e.g."House blueprint" is the class; the three identical houses built from it are three objects, each with its own address and paint colour.

Classes and Objects

Instantiation

Creating an object from a class is called instantiation, done with the new keyword. new allocates the object on the heap and hands you a reference to it.

Player p1 = new Player();   // one instance
Player p2 = new Player();   // a separate, independent instance

Each new produces a distinct object with its own field values.

Classes and Objects

The Top-Level Statements Reveal

Remember how the compiler wrapped your top-level code in a class with a Main method? Now it makes sense: there is no code outside a class in C#. Your program was always a class all along.

class Program
{
    static void Main(string[] args)
    {
        // your top-level code lived here
    }
}

The training wheels are off — everything is objects and classes.

Classes and Objects

Fields and Properties

An object's data is stored in fields, but we usually expose it through properties — a controlled gateway that looks like a field but can run code behind the scenes.

Fields and Properties

What Fields Are

A field is a variable that belongs to an object — its raw stored data. Each object has its own copy.

class Player
{
    public string name;   // a field
    public int health;    // a field
}

Exposing fields directly is convenient but gives you no control over how they're read or changed.

Fields and Properties

What Properties Are

A property looks like a field from the outside but is backed by get and set accessors — methods that run when the value is read or written. This lets you validate or react to changes.

class Player
{
    private int health;
    public int Health
    {
        get { return health; }
        set { health = value < 0 ? 0 : value; }  // never below 0
    }
}

Fields and Properties

Auto-Properties

When you don't need custom logic, an auto-property gives you the property syntax with a hidden backing field generated for you — concise and the everyday default.

class Player
{
    public string Name { get; set; }
    public int Health { get; private set; }  // read-only from outside
}

Fields and Properties

Getters and Setters

The get accessor returns the value; the set accessor receives it through the implicit value keyword. You can omit one to control access, or run any logic inside.

public string Name
{
    get => name;
    set => name = value.Trim();   // tidy input on the way in
}

Fields and Properties

Fields vs Properties

Field

Raw storage. Direct and fast, but no control — anyone can read or write any value.

Property

A controlled gateway. Same usage syntax, but it can validate, compute, restrict access, or react to changes.

Rule of thumb: keep fields private, and expose data through public properties.

Classes and Objects

Constructors

A constructor is special code that runs when an object is created, used to set it up — typically giving its fields their initial values.

Constructors

What a Constructor Is

A constructor is a method named after the class, with no return type. It runs once, when you new the object, guaranteeing it starts life in a valid state.

class Player
{
    public string Name;
    public Player()          // the constructor
    {
        Name = "Unnamed";
    }
}

Constructors

Default Constructor

If you write no constructor at all, C# supplies a hidden default constructor that takes no arguments and leaves fields at their default values. The moment you write any constructor of your own, that freebie disappears.

Player p = new Player();   // works via the default constructor

Constructors

Parameterized Constructor

A constructor can take parameters so callers supply starting values, making objects impossible to create in a half-built state.

class Player
{
    public string Name;
    public int Health;

    public Player(string name, int health)
    {
        Name = name;
        Health = health;
    }
}

Player hero = new Player("Aria", 100);

Constructors

Constructor Chaining

One constructor can call another with : this(...), avoiding duplicated setup code. This is constructor chaining.

public Player() : this("Unnamed", 100)
{
    // delegates to the constructor below
}

public Player(string name, int health)
{
    Name = name;
    Health = health;
}

Classes and Objects

Access Modifiers

Access modifiers control who can see and use a member. They're how C# enforces encapsulation — deciding what's part of a type's public face and what's hidden inside.

Access Modifiers

public

public members are visible to everyone — any code anywhere can read or call them. This is the deliberate, public-facing surface of a type.

public string Name;
public void Attack() { /* ... */ }

Access Modifiers

private

private members are visible only inside the same class. This is the default for class members, and the right choice for internal details you don't want others touching.

private int health;
private void Recalculate() { /* ... */ }

Access Modifiers

protected

protected members are visible inside the class and any class that inherits from it, but not to outside code. It's the bridge between a base class and its descendants.

protected int experience;

We'll use this once we reach inheritance.

Access Modifiers

internal

internal members are visible anywhere within the same assembly (project/compiled unit) but not to other assemblies. Good for code that's public across your project yet not part of its external API.

internal class LevelLoader { /* ... */ }

Access Modifiers

Why They Matter — Encapsulation

Access modifiers turn encapsulation from an idea into a rule the compiler enforces. By keeping fields private and exposing a small public surface, you:

  • Protect objects from invalid states.
  • Free yourself to change internals without breaking other code.
  • Make a type easier to understand and use correctly.

Classes and Objects

Static Members

Most members belong to an object. Static members belong to the class itself — shared by all instances, and usable without creating any object at all.

Static Members

What static Means

static ties a member to the type rather than to any one instance. There's exactly one copy, no matter how many objects exist — or even if none do.

Console.WriteLine(...);   // WriteLine is static — no Console object needed
int big = int.MaxValue;   // MaxValue is a static field on int

Static Members

Static Fields and Methods

A static field is shared state across all instances; a static method is called on the class, not an object. Static methods can't touch instance data, since there's no specific instance.

class Enemy
{
    public static int Count;       // shared by all enemies
    public Enemy() { Count++; }

    public static void ResetCount() => Count = 0;
}

Static Members

Static Classes

A class marked static can't be instantiated and holds only static members. It's a tidy home for utility functions that don't need any object state.

static class MathHelper
{
    public static int Square(int n) => n * n;
}

int result = MathHelper.Square(5);

Static Members

Static vs Instance

Instance member

Belongs to a specific object. Each object has its own copy; accessed through a variable like hero.Health.

Static member

Belongs to the class. One shared copy; accessed through the type like Enemy.Count.

Ask: "is this about one object, or about the whole type?" That answers whether it should be static.

Classes and Objects

Methods

A method is a function that lives inside a class. Everything you learned about functions — parameters, return types, ref/out — applies; the difference is that a method belongs to a type and can act on its object's data.

Methods

Functions Become Methods

The standalone functions we faked with top-level statements are, properly, methods on a class. Inside a method, you can read and change the object's own fields directly.

class Player
{
    public int Health;
    public void Heal(int amount)   // a method
    {
        Health += amount;          // acts on this object's field
    }
}

Methods

Method Overloading

Overloading lets several methods share a name as long as their parameters differ. The compiler picks the right one from the arguments you pass.

void Log(string message) { /* ... */ }
void Log(int code)        { /* ... */ }
void Log(string message, int code) { /* ... */ }

Log("Saved");        // calls the first
Log(404);            // calls the second
Log("Error", 500);   // calls the third

 

Structs

Section 15

Lightweight value types that look like classes but behave differently.

Gustave Doré engraving of a large toad — a small, self-contained creature of its own kind
Large ToadGustave Doré

Structs

Structs

A struct defines a custom type much like a class — with fields, properties and methods — but it's a value type. That single difference changes how it's copied, stored and used.

Structs

What a Struct Is

You declare a struct with the struct keyword. It's ideal for small, self-contained bundles of data, like a point or a colour.

struct Point
{
    public int X;
    public int Y;

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }
}

Point p = new Point(3, 4);

Structs

Struct vs Class

struct — value type

Copied on assignment; each variable is independent. Usually lives on the stack. No inheritance.

class — reference type

Shared by reference; copies point to the same object. Lives on the heap. Supports inheritance.

Point a = new Point(1, 1);
Point b = a;   // b is a full copy
b.X = 99;      // a.X is still 1

Structs

When to Use Structs

Reach for a struct when the data is:

  • Small — a handful of fields.
  • Logically a single value — a coordinate, a colour, a range.
  • Immutable or short-lived — copied cheaply, not shared.

Unity's Vector3 and Color are structs for exactly these reasons. When in doubt, use a class.

Structs

Limitations of Structs

  • No inheritance — a struct can't derive from another struct or class.
  • Copy cost — large structs are expensive to copy around.
  • Easy to mutate a copy by mistake, thinking you changed the original.
  • Being a value type, an uninitialized struct field is all-zeros, not null.

 

Generics

Section 16

Writing code once that works safely for many types.

Gustave Doré engraving of Baron Munchausen
Baron MunchausenGustave Doré

Generics

Generics

Generics let you write a class or method with a type placeholder, filled in when it's used. You get code reuse and full type safety — no casting, no losing track of types.

Generics

What Generics Are

The placeholder — written <T> by convention — stands in for a real type chosen by the caller. The same code then works for any type, while the compiler still checks every use.

List&lt;int&gt; numbers = new List&lt;int&gt;();    // T is int
List&lt;string&gt; names = new List&lt;string&gt;(); // T is string

You've already used generics every time you wrote List<...>.

Generics

Generic Classes

A generic class declares one or more type parameters in angle brackets, then uses them inside as if they were real types.

class Box<T>
{
    private T contents;
    public void Put(T item) => contents = item;
    public T Get() => contents;
}

Box<int> intBox = new Box<int>();
intBox.Put(42);
int value = intBox.Get();

Generics

Generic Methods

A single method can be generic even if its class isn't. The type parameter goes right after the method name.

void Swap<T>(ref T a, ref T b)
{
    T temp = a;
    a = b;
    b = temp;
}

int x = 1, y = 2;
Swap(ref x, ref y);   // T inferred as int

Generics

Type Constraints

Sometimes a generic type must meet a requirement — be a class, have a constructor, or implement an interface. The where clause adds those constraints, unlocking what you can do with T.

T CreateAndReturn<T>() where T : new()
{
    return new T();   // allowed because T must have a constructor
}

void Print<T>(T item) where T : IComparable { /* ... */ }

 

Memory in Depth

Section 17

Returning to the stack, the heap and the garbage collector — now that we have objects.

Gustave Doré engraving of Roland's descent — going down deeper into the layers below
Roland's DescentGustave Doré

Memory in Depth

Memory in Depth

Earlier we sketched memory in broad strokes. Now that you understand objects, let's look more closely at where data lives and how C# keeps it tidy.

Memory in Depth

The Stack in Depth

The stack is a region that grows and shrinks in strict last-in, first-out order. Each method call pushes a stack frame holding its local variables and parameters; returning pops it off — instantly freeing them.

It's extremely fast because allocation is just moving a pointer, but it's limited in size and tied to method calls.

Memory in Depth

The Heap in Depth

The heap is a larger, flexible pool for data whose lifetime isn't tied to a single method call — every object created with new. Allocation is more involved, and the memory stays alive as long as something references it.

Reference-type variables on the stack simply hold the address of their object on the heap.

Memory in Depth

Value vs Reference Types in Depth

Putting it together:

  • A local value type lives in the stack frame and dies with it.
  • A reference type lives on the heap; the stack holds only a reference to it.
  • A value type inside a class object lives on the heap too — wherever its owner lives.

So "value types are on the stack" is a useful simplification, not an absolute rule.

Memory in Depth

The Garbage Collection Cycle

flowchart LR
    A([new object]) --> B[Lives on the heap]
    B --> C{Still reachable?}
    C -->|Yes| B
    C -->|No| D[Marked as garbage]
    D --> E[("Memory reclaimed")]

Memory in Depth

Garbage Collection

The garbage collector (GC) periodically finds heap objects that nothing references any more and reclaims their memory automatically. An object becomes eligible the moment it's unreachable.

This frees you from manual cleanup, but it isn't free: collections take time, so in games we try to avoid creating needless garbage in hot code paths.

Memory in Depth

C# vs C and C++

C / C++

You allocate and free memory by hand. Maximum control and speed, but mistakes cause leaks, dangling pointers and crashes.

C#

The runtime manages the heap and the GC frees memory for you. Far safer and faster to write, at the cost of some control and occasional GC pauses.

This trade — safety and productivity over manual control — is central to why C# fits games and apps so well.

 

Collections

Section 18

Flexible, resizable containers for groups of data.

Gustave Doré engraving of a crowded tournament scene — a large gathered group
Deplorable Death of SavoisyGustave Doré

Collections

Collections Overview

Collections are types built to store and manage groups of objects. Unlike arrays, most can grow and shrink, and they come with rich methods for adding, finding and removing items.

Collections Overview

Why Collections Exist

Real programs rarely know how many items they'll hold up front — an inventory grows, enemies spawn and die. Collections handle that dynamism for you, so you don't manually resize and copy arrays.

They live in the System.Collections.Generic namespace and are all generic.

Collections Overview

Collections vs Arrays

Array

Fixed size, chosen at creation. Slightly faster and lighter. Best when the count is known and stable.

Collection (e.g. List)

Resizes automatically. Rich helper methods. Best when items are added and removed over time.

An array is the simple foundation; collections add convenience and flexibility on top.

Collections

List

A List is the workhorse collection: an ordered, resizable sequence of same-typed items. If you reach for one collection by default, it's this one.

List

What a List Is

A List<T> is like an array that can grow and shrink. T is the element type, fixed when you declare it, so it stays fully type-safe.

List<int> scores = new List<int>();
List<string> names = new List<string>();

List

Declaration and Initialization

Create an empty list, or initialize it with starting values using a collection initializer.

List<int> empty = new List<int>();
List<string> party = new List<string> { "Aria", "Ben", "Cleo" };

List

Adding and Removing Elements

Lists handle resizing for you as you add and remove.

List<string> party = new List<string>();
party.Add("Aria");          // append
party.Insert(0, "Ben");     // at a position
party.Remove("Aria");       // by value
party.RemoveAt(0);          // by index
Console.WriteLine(party.Count);  // how many

List

Iterating over a List

Walk a list with foreach when you want each item, or a for loop when you need the index.

foreach (string name in party)
{
    Console.WriteLine(name);
}

for (int i = 0; i < party.Count; i++)
{
    Console.WriteLine($"{i}: {party[i]}");
}

List

Common List Methods

  • Add / AddRange — append items.
  • Remove / RemoveAt / Clear — take items out.
  • Contains / IndexOf — search.
  • Count — current number of items.
  • Sort / Reverse — reorder in place.

Collections

Dictionary

A Dictionary stores data as key → value pairs, letting you look up a value instantly by its key instead of scanning through positions.

Dictionary

What a Dictionary Is

A Dictionary<TKey, TValue> maps unique keys to values. Think of a real dictionary: look up a word (key) to get its definition (value).

Dictionary<string, int> ages = new Dictionary<string, int>();

Dictionary

Key-Value Pairs

Each entry pairs a key with a value. Keys must be unique; values needn't be. The key is how you find the value again.

// key: player name   value: their score
Dictionary<string, int> scores = new Dictionary<string, int>();
scores["Aria"] = 1500;   // "Aria" is the key, 1500 the value

Dictionary

Declaration and Initialization

Start empty or seed it with pairs using an initializer.

Dictionary<string, int> scores = new Dictionary<string, int>
{
    ["Aria"] = 1500,
    ["Ben"]  = 1200
};

Dictionary

Adding, Removing, Accessing

Use the key like an index to read or write. TryGetValue safely handles missing keys.

scores["Cleo"] = 900;          // add or update
scores.Remove("Ben");          // remove by key
int aria = scores["Aria"];     // read (throws if missing)

if (scores.TryGetValue("Cleo", out int c))
{
    Console.WriteLine(c);      // safe lookup
}

Dictionary

Iterating over a Dictionary

Loop with foreach; each item is a KeyValuePair with .Key and .Value.

foreach (KeyValuePair<string, int> entry in scores)
{
    Console.WriteLine($"{entry.Key}: {entry.Value}");
}

Collections

Other Collections

List and Dictionary cover most needs, but C# offers specialised collections whose shape enforces a particular access pattern.

Other Collections

Queue

A Queue is first-in, first-out (FIFO) — like a line at a checkout. You Enqueue at the back and Dequeue from the front.

Queue<string> tasks = new Queue<string>();
tasks.Enqueue("load");
tasks.Enqueue("render");
string next = tasks.Dequeue();   // "load"

Other Collections

Stack

A Stack is last-in, first-out (LIFO) — like a stack of plates. You Push on top and Pop from the top. Great for undo history.

Stack<string> history = new Stack<string>();
history.Push("move1");
history.Push("move2");
string undo = history.Pop();     // "move2"

Other Collections

HashSet

A HashSet stores unique values with no order, and checks membership extremely fast. Adding a duplicate simply does nothing.

HashSet<string> visited = new HashSet<string>();
visited.Add("room1");
visited.Add("room1");            // ignored — already present
bool seen = visited.Contains("room1");   // true

Other Collections

When to Use Each

Queue

Process items in arrival order — job queues, message handling, breadth-first traversal.

Stack

Process the most recent first — undo/redo, backtracking, parsing.

HashSet

Track membership and uniqueness — "have I seen this?", removing duplicates.

Pick the collection whose rules match your access pattern, and the code reads its own intent.

 

Inheritance and Polymorphism

Section 19

Building types on top of types, and letting them behave in their own way.

Gustave Doré engraving of an elder lady — an ancestor passing traits down the line
Older LadyGustave Doré

Inheritance & Polymorphism

Inheritance

Inheritance lets one class build on another, reusing its data and behaviour and adding or changing what it needs. It models "is-a" relationships: a Dog is an Animal.

Inheritance

What Inheritance Is

Inheritance creates a new class from an existing one. The new class gets everything the original has, then extends it — avoiding duplicated code and capturing shared structure once.

class Animal
{
    public string Name;
    public void Eat() => Console.WriteLine($"{Name} eats");
}

class Dog : Animal
{
    public void Bark() => Console.WriteLine("Woof");
}

Base & Derived Class

1The base (parent) class is inherited from; the derived (child) class inherits and extends it.

e.g.Animal is the base class; Dog is a derived class that gains Name and Eat() while adding Bark().

Inheritance

The Colon Syntax

You declare inheritance with a colon: class Derived : Base. A class can inherit from exactly one base class in C#.

class Enemy { /* ... */ }
class Boss : Enemy { /* Boss is an Enemy, plus more */ }

Inheritance

What Gets Inherited

A derived class inherits the base's public, protected and internal members. It does not inherit:

  • private members (they exist but aren't accessible directly).
  • Constructors — though it can call them.

The derived class can then add new members or override existing behaviour.

Inheritance

The base Keyword

base refers to the parent class. Use it to call the base constructor, or to invoke base behaviour you're extending rather than fully replacing.

class Boss : Enemy
{
    public Boss(string name) : base(name)   // call Enemy's constructor
    {
    }

    public override void Attack()
    {
        base.Attack();        // do the normal attack...
        Console.WriteLine("...then a special move!");
    }
}

Inheritance & Polymorphism

Virtual and Override

By default a derived class can't change an inherited method. virtual and override are the opt-in mechanism that lets it provide its own version — the basis of polymorphism.

Virtual and Override

What virtual Means

Marking a base method virtual declares "derived classes may replace this." It still provides a default implementation that's used unless someone overrides it.

class Animal
{
    public virtual void Speak() => Console.WriteLine("...");
}

Virtual and Override

What override Means

A derived class uses override to supply its own version of a virtual method. Calls then run the derived version, even through a base-typed variable.

class Dog : Animal
{
    public override void Speak() => Console.WriteLine("Woof");
}

Animal a = new Dog();
a.Speak();   // "Woof" — the Dog version runs

Virtual and Override

Why They Exist

Together they let you write code against a general type and have each specific type behave correctly. A list of Animal can hold dogs and cats, and Speak() does the right thing for each — no if-chains on type.

Virtual and Override

The sealed Keyword

sealed is the opposite of leaving things open. On a class it prevents further inheritance; on an overridden method it stops further overriding down the chain.

sealed class FinalBoss : Enemy { /* no one can inherit from this */ }

public sealed override void Attack() { /* can't be overridden again */ }

Inheritance & Polymorphism

Abstract Classes

An abstract class is a base class that can't be instantiated on its own — it exists to be inherited from. It captures what a family of types shares while leaving some details for each child to fill in.

Abstract Classes

What abstract Means

Marking a class abstract says "this is an incomplete blueprint — only concrete subclasses can be created." You can't write new Shape() if Shape is abstract.

abstract class Shape
{
    public string Name;
}

// new Shape();  // error — abstract
Shape s = new Circle();  // fine — Circle is concrete

Abstract Classes

Abstract Methods

An abstract method has no body — just a signature. It forces every concrete subclass to provide an implementation, guaranteeing the behaviour exists.

abstract class Shape
{
    public abstract double Area();   // no body — must be overridden
}

class Circle : Shape
{
    public double Radius;
    public override double Area() => 3.14159 * Radius * Radius;
}

Abstract Classes

When to Use Abstract Classes

Use an abstract class when types share real structure and code, but one member can't be meaningfully defined at the base level.

  • There is a sensible shared base — Shape, Enemy, Weapon.
  • You want to share fields and concrete methods, not just a contract.
  • Each subclass must supply certain behaviour of its own.

Inheritance & Polymorphism

Interfaces

An interface is a pure contract: a list of members a type promises to provide, with no implementation and no data. It says what a type can do, never how.

Interfaces

What an Interface Is

Declared with interface (named with a leading I by convention), it lists method and property signatures only. Any type that implements it must supply all of them.

interface IDamageable
{
    void TakeDamage(int amount);
    int Health { get; }
}

Interfaces

How to Implement an Interface

Implement an interface with the same colon syntax as inheritance, then provide every member it declares.

class Player : IDamageable
{
    public int Health { get; private set; } = 100;
    public void TakeDamage(int amount) => Health -= amount;
}

Interfaces

Interface vs Abstract Class

Interface

A pure contract — no fields, (traditionally) no implementation. A type can implement many. Answers "what can it do?"

Abstract class

A partial base — can hold fields and shared code. A type can inherit only one. Answers "what is it?"

Rule of thumb: use an interface for a capability, an abstract class for a shared identity.

Interfaces

Multiple Interface Implementation

A class inherits from only one base class, but it can implement many interfaces — mixing in several capabilities at once.

class Player : Character, IDamageable, IMovable, ISaveable
{
    // must implement the members of all three interfaces
}

This is how C# gets the flexibility of multiple inheritance without its pitfalls.

Inheritance & Polymorphism

Polymorphism

Polymorphism — "many forms" — lets one piece of code work with objects of many types through a shared base or interface, each responding in its own way.

Polymorphism

What Polymorphism Is

It means a single name or type can take many forms. A variable typed as Animal can hold a Dog or a Cat, and calling Speak() runs the version that fits the actual object.

Polymorphism

Runtime Polymorphism

With virtual/override, C# decides at run time which method to call based on the object's real type — not the variable's declared type. This is runtime polymorphism.

List<Animal> zoo = new List<Animal> { new Dog(), new Cat() };
foreach (Animal a in zoo)
{
    a.Speak();   // each speaks correctly — Woof, then Meow
}

Polymorphism

Practical Examples

  • A render loop drawing every IDrawable, whatever its concrete type.
  • A damage system calling TakeDamage on anything IDamageable.
  • A save system serialising every ISaveable object the same way.

Polymorphism is what lets game systems treat wildly different objects uniformly.

 

Exception Handling

Section 20

Dealing with the things that go wrong while a program runs.

Gustave Doré engraving of Satan in torment — something gone badly wrong, caught mid-fall
Satan Knew PainGustave Doré

Exception Handling

Exception Handling

Even correct code meets bad input, missing files and broken connections. Exceptions are C#'s way of signalling and handling these runtime problems without crashing the whole program.

Exception Handling

What an Exception Is

An exception is an object representing an error that occurs while running. When something goes wrong, code throws an exception; unless it's caught, it stops the program.

int[] a = { 1, 2, 3 };
Console.WriteLine(a[10]);   // throws IndexOutOfRangeException

Exception Handling

try / catch / finally

Wrap risky code in try, handle failures in catch, and put cleanup that must always run in finally.

try
{
    int result = 10 / divisor;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Can't divide by zero");
}
finally
{
    Console.WriteLine("This always runs");
}

Exception Handling

Common Exceptions

  • NullReferenceException — using something that's null.
  • IndexOutOfRangeException — an array index past the end.
  • DivideByZeroException — integer division by zero.
  • FormatException — parsing text that isn't the expected format.
  • ArgumentException — a method got an invalid argument.

Exception Handling

Custom Exceptions

You can define your own exception types for errors specific to your program, by inheriting from Exception. They make failures self-describing and catchable on their own.

class OutOfManaException : Exception
{
    public OutOfManaException(string message) : base(message) { }
}

throw new OutOfManaException("Not enough mana to cast");

Exception Handling

Re-throwing Exceptions

Sometimes you catch an exception to log or react, then want it to keep propagating. Use a bare throw; to re-throw while preserving the original error and its stack trace.

try
{
    LoadSave();
}
catch (Exception ex)
{
    Log(ex);
    throw;          // re-throw; don't write "throw ex;" — it loses the trace
}

Exception Handling

The Exception Hierarchy

flowchart TD
    A[System.Exception] --> B[SystemException]
    A --> C[Your custom exceptions]
    B --> D[NullReferenceException]
    B --> E[IndexOutOfRangeException]
    B --> F[ArgumentException]
    F --> G[ArgumentNullException]

 

Week 1 Recap

Section 21

Looking back at the language — and ahead to the engine.

Gustave Doré engraving of an assault — pressing onward toward the next stage
The AssaultGustave Doré

Week 1 Recap

Everything We Covered

  • Foundations — what programs, languages and C# are, and how code runs.
  • Data — types, variables, operators, and conversions.
  • Control flow — functions, scope, conditionals and loops.
  • Memory — the stack, the heap and garbage collection.
  • OOP — classes, structs, generics, inheritance and polymorphism.
  • Working tools — collections, strings, and exception handling.

Week 1 Recap

How It All Connects

None of these topics stands alone. Types describe your data; variables hold it; functions and control flow act on it; classes bundle data with behaviour; the value/reference distinction explains how it all lives in memory; collections and exceptions are built from the very same ideas.

You now have a complete mental model of how a C# program is built and how it runs.

Week 1 Recap

What Comes Next — Unity

With the language under your belt, we step into Unity. Everything you've learned carries over directly:

  • Your scripts are classes that inherit from Unity's MonoBehaviour.
  • Vector3 and friends are structs; game objects are managed by reference.
  • Loops drive gameplay, and exceptions still guard against the unexpected.

Same language, new stage. See you in Unity.