The Analogy: Labelled Boxes on a Shelf
A variable is a labelled box. Three things describe it: the label you write on the front (the name), the shape of the box (the type, which decides what will fit and how much room it takes), and the contents (the value, which you can swap for another of the same shape).
The shape is chosen once, when the box goes on the shelf, and cannot change afterwards. That is what "statically typed" means. A box labelled int will hold whole numbers for its entire life; you cannot later drop a sentence into it. Python lets you re-shape the box at any moment and finds out at run time whether that was wise. C# refuses at build time, which is a smaller inconvenience than a customer finding the same mistake in production.
C# also insists a box be filled before you read it. Peering into an empty box is a compile error, not a garbage value — one of the sharper edges of C removed.
Syntax or Core Structure
using System;
class Program
{
const double TaxRate = 0.2;
static void Main()
{
int quantity = 12;
double weightKg = 2.5;
decimal unitPrice = 4.99m;
char grade = 'A';
bool inStock = true;
string label = "M4 bolt";
var lineTotal = quantity * unitPrice; // inferred as decimal
Console.WriteLine($"{label}: {quantity} @ {unitPrice:F2} = {lineTotal:F2}");
Console.WriteLine($"weight {weightKg} kg, grade {grade}, in stock {inStock}");
Console.WriteLine($"tax {lineTotal * (decimal)TaxRate:F2}");
Console.WriteLine($"lineTotal is a {lineTotal.GetType().Name}");
}
}
Output:
M4 bolt: 12 @ 4.99 = 59.88
weight 2.5 kg, grade A, in stock True
tax 11.98
lineTotal is a Decimal
Read the shape of a declaration as type, name, =, value. The value is optional at the point of declaration but mandatory before the first read.
Three details in that output repay attention. true prints as True because bool.ToString() returns the capitalised word — never compare printed output against the lowercase keyword. 'A' uses single quotes because a char is one character, while "M4 bolt" uses double quotes because a string is a sequence. And the tax line needed (decimal)TaxRate: C# will not silently mix decimal with double, so the conversion has to be written down.
The literal suffixes
long distance = 5_000_000_000L; // L: long
float ratio = 1.5f; // f: float
decimal money = 19.99m; // m: decimal
double plain = 1.5; // no suffix: double
int hex = 0x1F; // 31
int binary = 0b1010_0001; // 161
uint positive = 42u;
Underscores are digit separators; the compiler ignores them entirely, and 1_000_000 is easier to check than 1000000. Without a suffix a whole number is an int and a fractional number is a double, which is why decimal price = 4.99; fails to compile and 4.99m succeeds.
Technical Depth: Picking the Right Box
The numeric types
| Type | Size | Range or precision | Literal | Use it for |
|---|---|---|---|---|
byte | 1 byte | 0 to 255 | (byte)7 | raw bytes, pixel channels |
short | 2 bytes | -32,768 to 32,767 | (short)7 | rarely; packed data |
int | 4 bytes | ±2.1 billion | 7 | counts, indexes, ids — the default |
long | 8 bytes | ±9.2 quintillion | 7L | timestamps, file sizes, big totals |
float | 4 bytes | ~7 digits | 1.5f | graphics, where memory matters |
double | 8 bytes | ~15-17 digits | 1.5 | measurements, science — the default |
decimal | 16 bytes | 28-29 digits, base 10 | 1.5m | money, anything audited |
The unsigned variants (sbyte, ushort, uint, ulong) exist and are worth avoiding unless you are matching a binary format, because mixing signed and unsigned arithmetic produces conversions nobody expects.
char is 2 bytes and holds one UTF-16 code unit. bool is one byte in practice, and C# will not treat it as a number: if (count) is a compile error, unlike in C.
Definite assignment
int total;
Console.WriteLine(total); // CS0165: use of unassigned local variable 'total'
int counted;
if (DateTime.Now.Hour > 12) counted = 1;
Console.WriteLine(counted); // still CS0165 - not assigned on every path
A local variable has no default. The compiler traces every path into the read and refuses if any of them skips the write. A field on a class is different: it starts at 0, false, or null automatically, because objects are zeroed when allocated.
const, readonly, and var
const int MaxRetries = 3; // baked into the IL at every use site
static readonly DateTime Started = DateTime.Now; // computed once, at run time
readonly string _id = Guid.NewGuid().ToString(); // once per instance
const DateTime Bad = DateTime.Now; // ERROR: not a compile-time constant
const requires a value the compiler can evaluate itself, and it is copied into every place that reads it. That has a real consequence across assemblies: if a library changes a public const, code compiled against the old value keeps the old value until it is rebuilt. static readonly is read through a field at run time and has no such trap, so it is the safer choice for anything public.
var is inference, not a type. It needs an initializer, it cannot be a field, and var x = null; fails because null alone names no type.
Overflow is silent by default
int big = int.MaxValue;
Console.WriteLine(big + 1); // -2147483648 (wraps around)
Console.WriteLine((long)big + 1); // 2147483648 (widen first)
Console.WriteLine(checked(big + 1)); // throws OverflowException
Integer arithmetic wraps quietly. Widening one operand before the sum, as in the middle line, is the usual fix; checked turns the wrap into an exception when you would rather crash than compute nonsense. A whole project can be switched over with <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>.
Nullable value types
int? lastReading = null; // shorthand for Nullable<int>
lastReading = 42;
int shown = lastReading ?? 0; // 42, or 0 if it were still null
A plain int cannot be null, so a missing measurement has to be modelled either with a sentinel value (fragile) or with int? (honest). ?? supplies the fallback.
Real World Example: A Sensor Log Summary
Every variable kind earns its place here: constants for the fixed limits, accumulators that change on each pass, a nullable for a value that may never be set.
using System;
class Program
{
const int Capacity = 8; // compile-time limit
const double AlertAbove = 85.0;
static readonly string Sensor = "boiler-3"; // fixed once, at startup
static void Main()
{
double[] readings = { 71.5, 73.0, 72.25, 90.5, 68.75, 72.0 };
double min = double.MaxValue;
double max = double.MinValue;
double sum = 0;
int alerts = 0;
int? lastAlertIndex = null;
for (int i = 0; i < readings.Length; i++)
{
double r = readings[i];
if (r < min) min = r;
if (r > max) max = r;
sum += r;
if (r > AlertAbove)
{
alerts++;
lastAlertIndex = i;
}
}
double average = sum / readings.Length;
Console.WriteLine($"sensor {Sensor}, {readings.Length}/{Capacity} slots used");
Console.WriteLine($"min {min:F2} max {max:F2} avg {average:F2}");
Console.WriteLine($"alerts {alerts}, last at index {lastAlertIndex?.ToString() ?? "none"}");
}
}
Output:
sensor boiler-3, 6/8 slots used
min 68.75 max 90.50 avg 74.67
alerts 1, last at index 3
The six readings sum to 448.0, and 448.0 divided by 6 is 74.666..., which :F2 rounds to 74.67. Note that max prints as 90.50 rather than 90.5: the value is the same, the format string decides the digits.
Seeding min with double.MaxValue is the standard trick — the first comparison is then guaranteed to replace it. Seeding with 0 instead is a common bug that quietly reports a minimum of zero for any set of positive readings.
lastAlertIndex is int? because there may be no alerts at all. Index 0 is a perfectly valid answer, so -1 would work but relies on every reader knowing the convention; null says "no such thing" without a code word. lastAlertIndex?.ToString() ?? "none" reads as: call ToString only if there is a value, otherwise use "none".
AlertAbove is a const, not the bare number 85.0 inside the if. When the threshold changes it changes in one place, and the name explains the comparison to anyone reading the loop.
Common Mistakes
- Integer division where a fraction was meant.
int avg = 7 / 2;is3, anddouble avg = 7 / 2;is3.0— the division happens inintbefore the assignment ever sees it. Cast one operand:(double)7 / 2gives3.5. - Reading a local before assigning it.
int total; total += 5;fails with CS0165 because+=reads first. Initialise at the declaration:int total = 0;. - Accumulating money in a
double.0.1 + 0.2is0.30000000000000004, and comparing that to0.3with==is false. Usedecimalfor currency and a tolerance (Math.Abs(a - b) < 1e-9) when comparingdouble. - Assuming overflow will be reported.
int total = 50_000 * 50_000;does not raise anything at run time; it produces a negative number. Uselong, or turn on overflow checks. - Trying to make a runtime value
const.const string Path = Directory.GetCurrentDirectory();will not compile.static readonlyis the tool for values computed once at startup. - Single versus double quotes.
char grade = "A";fails andstring s = 'A';fails. Single quotes make achar, double quotes astring, and there is no automatic conversion in either direction. - Re-declaring a name in a nested block. Declaring
int iinside a loop whose header already declaresigives CS0136, even though the inner one looks separate. Pick a different name rather than shadowing. - Widening after the damage.
long ms = 1000 * 60 * 60 * 24 * 30;overflows inintfirst and then widens the wrong answer. Write1000L * 60 * 60 * 24 * 30so the whole expression is computed inlong.
Best Practices
- Initialise at the point of declaration whenever you can. It removes a class of compile errors and makes the intended starting state visible.
- Declare a variable in the narrowest block that needs it. A name introduced inside the loop cannot be misread outside it.
- Name for meaning, not for type:
elapsedMs,unitPrice,retryCount. Include the unit when a number has one —weightKgprevents an entire genre of bug. - Reach for
constfirst,readonlysecond, and a mutable variable only when the value genuinely changes. The compiler then enforces your intent. - Use
intfor counts anddoublefor measurements unless you have a specific reason otherwise. Choosingshortto save memory in a loop counter saves nothing and costs conversions. - Use
decimalthe moment money is involved, including for VAT rates and discounts that feed into a monetary total. - Break long literals with
_separators, and give repeated numbers a named constant.AlertAbovebeats an85.0that appears in four places. - Prefer
int?over a magic sentinel for "no value yet". The type then documents the possibility and the compiler makes you handle it.
Practice Exercises
- Declare one variable of each of
int,long,double,decimal,char,boolandstring, print each with itsGetType().Name, and add a comment next to each explaining what kind of data you would use it for. - Compute the average of
{ 7, 8, 10 }twice: once storing the sum in anintand dividing by the count, and once casting todoublebefore dividing. Print both to four decimals and explain the difference. - Take the sensor summary and add a
const double AlertBelow = 70.0, a second counter for low readings, and anint?holding the index of the first low reading. Print all of it, keeping"none"as the fallback text. - Write a program that starts from
int.MaxValue - 2and adds 1 five times in a loop, printing the value each pass. Then repeat the loop inside acheckedblock, catch theOverflowException, and print which iteration threw.