Roadmap › C# Language — Basics to Advanced › Module: Getting Started
Lessons in this course (38)

3. Data types, numbers and type conversion

Basic★ Must knowLesson 3 of 38
C# keyword.NET typeSizeRange / precisionLiteral
byte / sbyteByte / SByte1 byte0–255 / −128–127255
short / ushortInt16 / UInt162 bytes±32,767 / 0–65,535100
int / uintInt32 / UInt324 bytes±2.1 billion42, 42u
long / ulongInt64 / UInt648 bytes±9.2 × 10¹⁸42L
floatSingle4 bytes~6–9 digits, binary floating point1.5f
doubleDouble8 bytes~15–17 digits, binary floating point (default for decimals)1.5
decimalDecimal16 bytes28–29 digits, base-10 — use for money1.5m
charChar2 bytesOne UTF-16 code unit'A'
boolBoolean1 bytetrue / falsetrue
stringStringreferenceImmutable text"text"
objectObjectreferenceBase of every type—
csharp
Console.WriteLine(0.1 + 0.2 == 0.3);       // False — binary floating point can't store 0.1 exactly
Console.WriteLine(0.1m + 0.2m == 0.3m);    // True  — decimal is exact for base-10 values
int big = 1_000_000;                        // digit separators
int hex = 0xFF, bin = 0b1010;

// Integer overflow wraps silently by default...
int max = int.MaxValue;
int wrapped = unchecked(max + 1);           // -2147483648
// ...unless you ask for checking
try { int boom = checked(max + 1); } catch (OverflowException) { Console.WriteLine("Overflow!"); }

Console.WriteLine(7 / 2);     // 3   — integer division truncates
Console.WriteLine(7 / 2.0);   // 3.5
Console.WriteLine(7 % 2);     // 1   — remainder
Console.WriteLine(Math.Round(2.5));                              // 2 — banker's rounding (to even) by default
Console.WriteLine(Math.Round(2.5, MidpointRounding.AwayFromZero)); // 3

Type conversion:

KindExampleNotes
Implicit (widening)long l = intValue; double d = intValue;Safe, no data loss, no syntax needed
Explicit cast (narrowing)int i = (int)3.99; → 3May lose data; truncates decimals
Convert classConvert.ToInt32("42"), Convert.ToInt32(3.5) → 4Rounds to even; null → 0
Parseint.Parse("42")Throws FormatException on bad input
TryParseint.TryParse(input, out var n)Returns false instead of throwing — use for user input
as / isobj as string, obj is int nReference/pattern conversions without exceptions
csharp
if (int.TryParse(Console.ReadLine(), out int qty) && qty > 0)
    Console.WriteLine($"Ordering {qty}");
else
    Console.WriteLine("Please enter a positive number");

decimal price = decimal.Parse("1,234.50", NumberStyles.Number, CultureInfo.InvariantCulture); // culture decides what , and . mean

Interview tip: "Why decimal for money?" — double is binary and can't represent 0.1 exactly, so sums drift (0.1 + 0.2 != 0.3). decimal stores base-10 digits exactly, at the cost of speed and memory.