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 type | Size | Range / precision | Literal |
|---|---|---|---|---|
byte / sbyte | Byte / SByte | 1 byte | 0–255 / −128–127 | 255 |
short / ushort | Int16 / UInt16 | 2 bytes | ±32,767 / 0–65,535 | 100 |
int / uint | Int32 / UInt32 | 4 bytes | ±2.1 billion | 42, 42u |
long / ulong | Int64 / UInt64 | 8 bytes | ±9.2 × 10¹⁸ | 42L |
float | Single | 4 bytes | ~6–9 digits, binary floating point | 1.5f |
double | Double | 8 bytes | ~15–17 digits, binary floating point (default for decimals) | 1.5 |
decimal | Decimal | 16 bytes | 28–29 digits, base-10 — use for money | 1.5m |
char | Char | 2 bytes | One UTF-16 code unit | 'A' |
bool | Boolean | 1 byte | true / false | true |
string | String | reference | Immutable text | "text" |
object | Object | reference | Base 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)); // 3Type conversion:
| Kind | Example | Notes |
|---|---|---|
| Implicit (widening) | long l = intValue; double d = intValue; | Safe, no data loss, no syntax needed |
| Explicit cast (narrowing) | int i = (int)3.99; → 3 | May lose data; truncates decimals |
Convert class | Convert.ToInt32("42"), Convert.ToInt32(3.5) → 4 | Rounds to even; null → 0 |
Parse | int.Parse("42") | Throws FormatException on bad input |
TryParse | int.TryParse(input, out var n) | Returns false instead of throwing — use for user input |
as / is | obj as string, obj is int n | Reference/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 . meanInterview tip: "Why decimal for money?" —
doubleis binary and can't represent 0.1 exactly, so sums drift (0.1 + 0.2 != 0.3).decimalstores base-10 digits exactly, at the cost of speed and memory.