Variables are like labeled boxes where you store data. You put something in, give it a name, and pull it out whenever you need it. Every C# program uses variables constantly, so this is one of the first things to get comfortable with.
Declaring Variables
In C#, you declare a variable by specifying its type followed by its name:
int age; // Declares an integer variable named age
string name; // Declares a string variable named name
double price; // Declares a decimal number variable
After declaring, you can assign a value:
age = 25;
name = "Alice";
price = 19.99;
Or you can combine declaration and assignment in one step:
int age = 25;
string name = "Alice";
double price = 19.99;
Type Inference with var
C# can figure out the type for you using the var keyword. When you write var, the compiler looks at what you're assigning and determines the type automatically:
var age = 25; // Compiler figures out this is int
var name = "Alice"; // Compiler figures out this is string
var price = 19.99; // Compiler figures out this is double
This isn't magic โ the variable still has a fixed type. var just saves you typing. Once the compiler decides it's an int, you can't store text in it later.
Naming Rules
C# has some rules for variable names, plus common conventions the community follows:
- Names must start with a letter or underscore.
- They can contain letters, digits, and underscores.
- They're case-sensitive โ
myVarandMyVarare different. - They can't be reserved keywords like
int,class, orstatic. - Convention: use camelCase for local variables (
firstName,totalPrice).
int myVar = 10; // Valid
int _count = 5; // Valid, underscore prefix is allowed
int 2fast = 3; // Invalid โ starts with a digit
int class = 7; // Invalid โ class is a keyword
Try it Yourself โ
Assigning Values
The assignment operator (=) puts a value into your variable. You can also reassign variables โ change what they store:
int score = 10;
score = 20; // Now score is 20, the old value is gone
score = score + 5; // Now score is 25
Variables must be assigned a value before you use them. The compiler will yell at you if you try to read from an unassigned variable. This is actually a good thing โ it catches bugs before they happen.