C# — The Language You Write
Throughout this course you will build ReadingRoom, a small lending-library API with books, members and loans. Every line of it is C#. Before any web code, you need to read C# comfortably: what a type is, what a class is, and why the compiler rejects code before you ever run it.
The rule
Every value has a type, and the compiler checks it before anything runs.
C# is statically typed. When you declare a variable, its type is fixed. If you try to put the wrong kind of value in it, the build fails — you find the mistake at your desk, not in production.
int copies = 3; // a whole number
string title = "Dune"; // text
decimal lateFee = 0.50m; // money: use decimal, not double
bool isOverdue = false;
var year = 1965; // still an int: var infers, it does not loosenTypes you build yourself are classes and records. A record is a short way to write a type that mostly carries data:
public record Book(int Id, string Title, string Author, int Year);
var book = new Book(1, "Dune", "Frank Herbert", 1965);
Console.WriteLine(book.Title); // DuneModern projects switch on nullable reference types. Then string means "never null" and string? means "might be null", and the compiler warns when you forget to check.
The shortcut
When you read an unfamiliar line of C#, find the type on the left first. It tells you what the value can hold and what you can do with it. var is not a type of its own; read the right-hand side to find the real one.
Find the declared type
In
List<Book> shelf = new();the type isList<Book>: a growable list that only acceptsBookvalues.
The trap: thinking var makes C# dynamic like JavaScript. It does not. var x = 5; x = "five"; fails, because x became an int on the first line.
Drills
Answer fast — trust the rule.
What is the type of total in var total = 12;?
When does C# report that int copies = "three"; is wrong?
Which type fits a library's late fee of 0.50 best?
With nullable reference types on, what does string? Subtitle tell you?
Remember
- Every value has a type, and the compiler checks it before anything runs.
- Read the type on the left first; resolve
varfrom the right-hand side. varis still static typing, and?means "may be null — check it".
