C#, lesson 2
A variable is a named box that holds a value. C# is statically typed: every variable has a type, and the compiler checks that you only put matching values in it.
using System;
int lives = 3;
double speed = 2.5;
string player = "Robin";
bool gameOver = false;
char grade = 'A';
lives = lives - 1; // you can change the value...
// lives = "three"; // ...but not the type: compile error CS0029
Console.WriteLine($"{player} has {lives} lives");| Type | Holds | Example |
|---|---|---|
int | whole numbers up to about ±2.1 billion | 42, -7 |
long | much larger whole numbers | 8_000_000_000L |
double | fast decimal numbers for science and games | 3.14, 1.5e3 |
decimal | exact decimal numbers, ideal for money | 19.99m |
bool | true or false | true |
char | a single character, in single quotes | 'Z' |
string | text, in double quotes | "hello" |
The lowercase names are C# keywords that stand for .NET types: int is System.Int32,
string is System.String, and so on. Use the keywords; they are the normal style.
Underscores in number literals only help you read them: 1_000_000 is one million. Suffixes
pick the type of a literal: L for long, m for decimal, f for float.
A double stores numbers in binary, so many everyday decimals such as 0.1 cannot be stored
exactly. The tiny errors show up when you add them:
decimal stores base-10 digits exactly, so prices and bank balances add up the way you expect.
It also remembers how many decimal places you wrote: 2.50m prints as 2.50. It is slower than
double, which does not matter for most programs.
When you print a bool, C# writes True or False with a capital letter, even though the
keywords in your code are lowercase.
Inside methods and top-level code you can write var and let the compiler infer the type from
the value:
The variable is still strongly typed; you just did not spell the type out. var needs a starting
value. Use it when the type is obvious from the right-hand side.
A const is a value fixed when the program is compiled. Trying to change it is a compile error.
C# names constants in PascalCase:
Names are case sensitive. Local variables use camelCase (totalScore), while types, methods
and constants use PascalCase (TotalScore). A name cannot start with a digit or be a keyword
such as class. Choose names that explain the value: price beats p.
2 exercises to try what you just read.
Console.WriteLine(0.1 + 0.2); // 0.30000000000000004
Console.WriteLine(0.1m + 0.2m); // 0.3var city = "Lisbon"; // string
var count = 12; // int
var total = 4.50m; // decimalconst int MaxPlayers = 4;
const decimal TaxRate = 0.2m;
// MaxPlayers = 5; // error CS0131Title: Space Cats
Year: 2026
Price: 12.50
3D: True
Row: FTotal: 3.30