Variables and types
Store values in named variables and pick the right type for each kind of data.
12 min read
You will learn
- Declare and assign variables
- Choose between the built-in types int, double, decimal, bool, char and string
- Use var and const correctly
- Convert between types safely
What is a variable?
A variable is a named box that holds a value. You give it a type (what kind of value can go in the box) and a name (so you can refer to it later):
int age = 36;
//│ │ └── the value
//│ └──────── the name
//└───────────── the typeYou can change what's in the box later — but only to another value of the same type:
int age = 36;
age = 37; // ✅ fine
age = age + 1; // ✅ now 38
age = "old"; // ❌ compile error: a string is not an intC# is statically typed
Every variable's type is fixed when the code is compiled. The compiler catches type mistakes before your program ever runs — one of the big reasons C# code tends to be reliable.
The built-in types you'll use most
| Type | Holds | Example |
|---|---|---|
int | Whole numbers (±2.1 billion) | int score = 42; |
long | Very large whole numbers | long views = 8_000_000_000; |
double | Decimal numbers, fast but approximate | double height = 1.65; |
decimal | Exact decimal numbers — use for money | decimal price = 19.99m; |
bool | true or false | bool isAdmin = false; |
char | A single character, in single quotes | char grade = 'A'; |
string | Text, in double quotes | string name = "Ada"; |
Notice the m suffix on 19.99m. Without it, 19.99 is a double, and C# won't silently turn it into a decimal.
Never use double for money
0.1 + 0.2 as double gives 0.30000000000000004. As decimal it gives exactly 0.3. Prices, balances and invoices should always be decimal.
Naming rules
- Use camelCase for local variables:
firstName,totalPrice. - Names can contain letters, digits and
_, but can't start with a digit. - Names are case-sensitive:
ageandAgeare different variables. - Pick names that describe the value:
daysUntilDeadlinebeatsd.
var — let the compiler infer the type
When the type is obvious from the right-hand side, you can write var:
var city = "Casablanca"; // string
var year = 2026; // int
var ratio = 0.75; // doubleThe variable still has a fixed type — var just saves you from typing it. You can't write var x; without a value, because the compiler would have nothing to infer from.
const — values that never change
const int MaxLoginAttempts = 5;
const double Pi = 3.14159;
MaxLoginAttempts = 6; // ❌ compile errorUse const for fixed values known at compile time. Constants are conventionally named in PascalCase.
Converting between types
Implicit conversions happen automatically when no data can be lost:
int whole = 10;
double d = whole; // ✅ 10.0 — every int fits in a doubleExplicit conversions (casts) are required when data might be lost:
double price = 9.99;
int rounded = (int)price; // 9 — the .99 is cut off, not rounded!Parsing turns text into a number:
int a = int.Parse("123"); // 123
int b = int.Parse("hello"); // 💥 throws FormatException at runtime
if (int.TryParse("hello", out int c))
Console.WriteLine(c);
else
Console.WriteLine("Not a number"); // ✅ safe: no exceptionTip
Prefer TryParse whenever the text comes from a user or a file — you can't trust it to be a valid number.
Try it
Run this, then experiment: change "42" to "forty-two", or remove the (int) cast and read the compiler error.
C# runtime not loaded
Putting values into strings
String interpolation — a $ before the string, and expressions in {braces} — is the cleanest way to build text:
string name = "Ada";
int age = 36;
Console.WriteLine($"{name} is {age} years old.");
// Ada is 36 years old.
Console.WriteLine($"Next year she'll be {age + 1}.");
// Next year she'll be 37.Key takeaways
- A variable = type + name + value, and its type never changes.
intfor whole numbers,doublefor measurements,decimalfor money,bool,char,string.varinfers the type;constmakes a value unchangeable.- Widening conversions are implicit; narrowing ones need a cast; text needs
Parse/TryParse.
Exercise
Declare three variables — name = "Ada", age = 36 and height = 1.65 — using appropriate types. Then print exactly: Ada is 36 years old and 1.65 m tall.
C# runtime not loaded
Hint 1
name is text → string. age is a whole number → int. height has a decimal point → double.
Hint 2
Put a $ before the string and wrap variables in braces: $"{name} is ..."
Show solution
string name = "Ada";
int age = 36;
double height = 1.65;
Console.WriteLine($"{name} is {age} years old and {height} m tall.");Quiz
4 questions · 3 correct to pass1.Which type should you use to store a product price like 19.99 in a shopping app?
2.What is the type of x in `var x = 10;`?
3.What happens when you compile `int count = "5";`?
4.Which line will NOT compile?
To complete this lesson
- ○ Solve the exercise
- ○ Pass the quiz (3/4 correct)