C# · Lesson 1

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); // 2

C# 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";  // string

Practical 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 → decimal

C# makes you choose numeric domains

This does not compile:

var price = 10m; // decimal
var tax = 0.23;   // double

Console.WriteLine(price * tax); // compile-time error

That 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.30

Compatible 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.5

Here, 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:

  1. What does var mean in C#, and what does it not mean?
  2. Why does 5 / 2 print 2?
  3. What is the difference between 5.0, 5f, and 5m?
  4. Why does decimal * double fail to compile?