In the last lesson, you saw a variable in action when we used string name = Console.ReadLine();.
Now let us talk about what variables really are and the different types of data you can work with.
Think of a variable as a labeled box. You put something inside the box, give it a name, and then you can refer to that box whenever you need what is inside. In programming, variables store data.
Declaring Variables
In C#, you declare a variable by specifying its type and giving it a name. Here is the pattern:
type name = value;
For example:
int age = 25;
string name = "Amina";
double height = 5.6;
bool isStudent = true;
See how each variable has a different type? That is because C# is a strongly-typed language. This means you have to tell it what kind of data each variable will hold. It might seem annoying at first, but trust me, it saves you from a lot of bugs down the road.
Common Data Types
Here are the data types you will use most often:
intโ whole numbers like 1, 42, -7, 100doubleโ decimal numbers like 3.14, -0.5, 100.0floatโ also decimal numbers, but uses less memory (you need to add an 'f' suffix: 3.14f)decimalโ high-precision decimals, great for money calculationsstringโ text like "Hello", "Kano", "25" (yes, numbers in quotes are strings)boolโ eithertrueorfalsecharโ a single character like 'A', 'z', '9'
Naming Rules
You cannot just name variables whatever you want. There are a few rules:
- Names must start with a letter or underscore
- They can contain letters, numbers, and underscores
- You cannot use C# keywords like
int,string,classas variable names - C# is case-sensitive โ
ageandAgeare two different variables
The convention in C# is to use camelCase for variables (first word lowercase, subsequent words capitalized) and PascalCase for class names (each word capitalized).
int studentCount = 30; // camelCase
string firstName = "Bilal"; // camelCase
class StudentRecord { } // PascalCase
Using Variables
Once you have declared a variable, you can use it in your code. You can print it, do math with it, combine it with other variables, and more:
string name = "Fatima";
int age = 22;
Console.WriteLine("Name: " + name);
Console.WriteLine("Age: " + age);
Console.WriteLine("Next year, " + name + " will be " + (age + 1));
Notice how we use the + operator to combine strings with other values. This is called
string concatenation. It works, but there is a better way to do it โ string interpolation.
We will cover that soon.