typestar

Numbers & casts in C#

Widening is automatic, narrowing needs a cast, and money gets decimal.

int count = 42;
double precise = count;          // widening happens on its own
int back = (int)3.99;            // narrowing needs a cast, and truncates
decimal price = 19.99m;          // decimal for money, never double

long big = 7_000_000_000;
int parsed = int.Parse("123");
Console.WriteLine($"{precise} {back} {price * 2} {big} {parsed + 1}");

How it works

  1. An int fits in a double, so that conversion happens silently.
  2. (int)3.99 truncates to 3 — narrowing always asks for an explicit cast.
  3. decimal is exact base-10 for money; _ keeps long literals readable.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
350
Tokens
49
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 33 seconds.

Type this snippet

Step 2 of 3 in Variables & types, step 2 of 29 in Language basics.

← Previous Next →

Numbers & casts in other languages