Declaring variables
Learn to declare variables of type int, double, string and bool.
What is a variable?
A variable is a box that stores a value under a name. In C# every variable has a type that tells what the box holds.
Use int for whole numbers, double for decimals, string for text and bool for true-false.
Example: int age = 25; makes age hold 25. string name = "Alex"; stores a piece of text.
To print the value you write Console.WriteLine(name);. Stating the type up front lets the compiler catch mistakes early.
Choosing a type
Picking the right type matters for both memory and readability. int is for whole numbers: age, count, year.
double is for decimals: price, temperature, distance. string holds text: name, city, message.
bool takes only two values: true or false. It is ideal for flags: isActive, hasPermission.
The wrong type causes surprises; for example, keeping an age in a string makes arithmetic awkward.
Exercise Print name and age
Assign 25 to age and "Alex" to name. Then print each on its own line with Console.WriteLine.
Show example solution
First write Console.WriteLine(name);, then add Console.WriteLine(age);.
Example solution:
int age = 25;
string name = "Alex";
Console.WriteLine(name);
Console.WriteLine(age);
Test yourself
-
Which is a valid int declaration?
- int age = 25;
- int age = "25";
- int age = 25.5;
- int age = true;
Show answer
int age = 25; — Correct! int declares a whole-number variable and 25 is a whole number.
-
Write the whole-number type
____ age = 25;Show answer
int age = 25; -
Match each type to an example value
- int
- 42
- double
- 3.14
- string
- "Hello"
- bool
- true