Choosing the right numeric type and understanding static typing prevents overflow and rounding bugs.
C# is statically typed: each variable has a type fixed at compile time. Declare it with an explicit type (int count = 3;) or let the compiler infer it with var (var price = 9.99m;). var is still static typing: the type is decided once and cannot change.
Common built-in types:
int(32-bit) andlong(64-bit) integers;byte,shortand unsigned variants exist too.double(64-bit binary floating point) for science and graphics;floatfor 32-bit.decimal(128-bit, base-10) for money:0.1m + 0.2mis exactly0.3m.bool(true/false),char(one UTF-16 code unit,'a'), andstring.
Literal suffixes pick the type: 10L is long, 1.5f float, 1.5m decimal. Underscores improve readability: 1_000_000.
Integer division truncates (7 / 2 is 3). Integer arithmetic silently wraps on overflow by default; wrap code in checked { } or enable the CheckForOverflowUnderflow project setting to get an OverflowException instead.
Conversions that can lose information need an explicit cast: int i = (int)3.9; gives 3. Widening conversions (int to long or double) are implicit. To turn text into numbers use int.Parse("42"), or int.TryParse(s, out var n), which returns false instead of throwing on bad input.
const declares a compile-time constant; readonly fields are set once at construction.
Example
int count = 3;
var price = 9.99m; // decimal, inferred
double ratio = 7 / 2; // integer division first
Console.WriteLine(ratio); // 3
Console.WriteLine(7 / 2.0); // 3.5
Console.WriteLine(0.1 + 0.2 == 0.3); // False (double)
Console.WriteLine(0.1m + 0.2m == 0.3m); // True (decimal)
Console.WriteLine((int)3.9); // 3
Console.WriteLine(count * price); // 29.97
int big = int.MaxValue;
Console.WriteLine(big + 1); // -2147483648 (wraps)
if (int.TryParse("12x", out var n)) Console.WriteLine(n);
else Console.WriteLine("not a number"); // not a numberRemember
- var infers a fixed static type; it is not dynamic
- Use decimal for money, double for measurements
- Integer division truncates and int overflow wraps unless checked
- Prefer TryParse for user input
Watch out for
- Writing double x = 7 / 2 and expecting 3.5: both operands are ints.