var is not JavaScript var
Today’s win: predict C# numeric expressions by reading their static types. This is the first place where a TypeScript brain can make the wrong guess.
The one-sentence model
In C#, var means: the compiler infers one static type now, and the variable keeps that type.
It is closer to TypeScript inference than JavaScript var. After var x = 5;, x is an int. You cannot later assign "five" to it.
Integer division
If both sides are int, the result is also int. The fractional part is discarded.
var x = 5;
var y = 2;
Console.WriteLine(x / y); // 2C# does not silently switch to floating-point just because the mathematical answer has a decimal part.
Numeric literal defaults
These defaults matter because they decide which operator overload C# chooses.
var a = 5; // int
var b = 5.0; // double
var c = 5f; // float
var d = 5m; // decimal
var e = "5"; // stringPractical rule
int: counts and small whole numbers.double: default floating-point measurements.float: smaller floating-point, usually only when required.decimal: money-like precise base-10 values.
Suffixes
5 → int5.0 → double5f → float5m → decimalC# makes you choose numeric domains
This does not compile:
var price = 10m; // decimal
var tax = 0.23; // double
Console.WriteLine(price * tax); // compile-time errorThat refusal is good. Converting decimal to double can lose base-10 precision, and converting arbitrary double to decimal is not always safe. The compiler asks you to be explicit.
Use one numeric domain intentionally:
var price = 10m;
var tax = 0.23m;
Console.WriteLine(price * tax); // 2.30Compatible numeric promotion
When the operands are compatible, C# can promote the narrower value for the operation:
var count = 5; // int
var total = 2.0; // double
var result = count / total;
Console.WriteLine(result); // 2.5Here, count is promoted from int to double for the division, so the result is double.
Retrieval checkpoint — next time
Before we continue, answer these from memory:
- What does
varmean in C#, and what does it not mean? - Why does
5 / 2print2? - What is the difference between
5.0,5f, and5m? - Why does
decimal * doublefail to compile?