02. Variables & Types
A variable is a named box in memory that holds a value. In C# every box has a fixed type, so the compiler knows what fits inside and stops mistakes before your program ever runs.
Declaring variables
Write the type, a name, and optionally an initial value. You can change the value later, but never the type. With var, the compiler infers the type from the value on the right. It is still strongly typed: city is a string forever.
int age = 30;
string name = "Ada";
bool isAdmin = false;
age = 31;
var city = "Jakarta";
var score = 9.5;
Console.WriteLine($"{name} is {age}, admin: {isAdmin}");
Console.WriteLine($"{city} is a {city.GetType().Name}");
Console.WriteLine($"{score} is a {score.GetType().Name}");Ada is 31, admin: False Jakarta is a String 9.5 is a Double
Naming convention: local variables use camelCase (isAdmin). Types and constants use PascalCase (MaxLoginAttempts).
Constants
A constant is a value that never changes. Mark it with const. The compiler rejects any attempt to reassign it, and readers instantly know it is fixed.
const double Pi = 3.14159;
const int MaxLoginAttempts = 3;
double radius = 2;
double area = Pi * radius * radius;
Console.WriteLine($"Area: {area}");
Console.WriteLine($"You have {MaxLoginAttempts} attempts.");Area: 12.56636 You have 3 attempts.
Primitive types
These are the built-in types you will use every day. Pick the smallest one that safely fits your data, but in practice int, double, decimal, bool, and string cover most code.
| Type | Size | Holds |
|---|---|---|
byte | 1 byte | 0 to 255 |
short | 2 bytes | -32,768 to 32,767 |
int | 4 bytes | about ±2.1 billion |
long | 8 bytes | about ±9.2 quintillion |
float | 4 bytes | ~7 digits of precision |
double | 8 bytes | ~15 digits of precision |
decimal | 16 bytes | ~28 exact decimal digits |
char | 2 bytes | one Unicode character |
bool | 1 byte | true or false |
Number literals need a suffix when they are not the default: L for long, f for float, m for decimal. Underscores in numbers are ignored, they just help readability.
byte level = 255;
short temperature = -40;
int population = 280_000_000;
long distance = 9_460_730_472_580_800L;
float ratio = 0.5f;
double average = 1.0 / 3;
decimal price = 19.99m;
char grade = 'A';
bool isActive = true;
Console.WriteLine($"{level} {temperature} {population} {distance}");
Console.WriteLine($"{ratio} {average} {price}");
Console.WriteLine($"{grade} {isActive}");
Console.WriteLine($"int range: {int.MinValue} to {int.MaxValue}");255 -40 280000000 9460730472580800 0.5 0.3333333333333333 19.99 A True int range: -2147483648 to 2147483647
string is not in the table. It is a class, not a primitive, but it is so common that C# gives it a keyword and literal syntax. More in lesson 12.
decimal for money
float and double store numbers in binary, so values like 0.1 are only approximated. decimal stores them in base 10, exactly. It is slower, but for prices and balances, correct beats fast.
double a = 0.1 + 0.2;
decimal b = 0.1m + 0.2m;
Console.WriteLine($"double: {a == 0.3} ({a:R})");
Console.WriteLine($"decimal: {b == 0.3m} ({b})");double: False (0.30000000000000004) decimal: True (0.3)
Overflow
When a value grows past its type's maximum, it silently wraps around to the minimum. Wrap a risky calculation in checked to throw an error instead of getting a wrong number.
byte counter = 255;
counter++;
Console.WriteLine($"Wrapped around: {counter}");
try
{
byte safe = 255;
checked
{
safe++;
}
}
catch (OverflowException)
{
Console.WriteLine("checked caught the overflow");
}Wrapped around: 0 checked caught the overflow
Scope
A variable only exists inside the block ({ }) where it was declared. bonus disappears after its closing brace; total, declared outside, lives on.
var total = 0;
{
var bonus = 5;
total += bonus;
Console.WriteLine($"Inside the block: bonus = {bonus}, total = {total}");
}
Console.WriteLine($"Outside the block: total = {total}");Inside the block: bonus = 5, total = 5 Outside the block: total = 5
API models are classes built from these types. Use decimal for money, int or long for IDs, and bool for flags. They map directly to database columns and JSON values.
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = "";
public decimal Price { get; set; }
public bool InStock { get; set; }
}