Variables
Learn how to declare, initialize, and use variables in C#, including type inference with var.
What is a Variable?
A variable is a named location in memory that stores a value. In C#, every variable has a specific type, and that type cannot change once declared — this is exactly what it means for C# to be a statically typed language, as covered in the introduction lesson. Once you declare int age, that variable will hold an integer for its entire lifetime; it can never later hold a string.
Declaring Variables
int age = 25;double price = 19.99;string name = "Alex";bool isActive = true;
Console.WriteLine($"{name} is {age} years old.");Click Run to see what this code prints.
A variable can also be declared without an initial value, and assigned later — as long as it is assigned something before it is ever read.
int score; // declared, not yet assignedscore = 100; // assigned laterConsole.WriteLine(score);Real-World Analogy
Think of a variable as a labeled storage box. int age = 25 is like a box labeled "age" that can only ever hold whole numbers, currently holding the number 25. You can swap out what's inside (reassign the value), but you can't suddenly decide the box now holds paper documents (a string) instead of numbers — the box's type was fixed the moment you built it.
Naming Rules & Conventions
- Must start with a letter or underscore, not a digit — 1age is invalid, but age1 and _age are both fine.
- Can contain letters, digits, and underscores after the first character.
- Case-sensitive — `age` and `Age` are treated as two completely different variables.
- By convention, use camelCase for local variables and parameters (e.g. `studentName`, `totalPrice`).
- By convention, use PascalCase for method names, class names, and properties (e.g. `CalculateTotal`, `StudentName`) — covered further once classes are introduced.
- Avoid single-letter names except for very short-lived loop counters (like i in a for loop, covered in the loops lesson).
C# reserves a specific set of keywords (like class, if, int) that cannot be used as variable names — but you can still use a reserved word as an identifier by prefixing it with @, e.g. @class, though this is rarely done in practice and mostly exists for interoperability with other .NET languages that don't share the same reserved word list.
Type Inference with var
The `var` keyword lets the compiler infer the type from the assigned value, rather than you spelling it out explicitly. The variable is still strongly, statically typed — `var` is purely a shorthand resolved at compile time, not a way to skip typing altogether or opt into dynamic behavior.
var count = 10; // inferred as intvar price = 19.99; // inferred as doublevar name = "Alex"; // inferred as stringvar isReady = true; // inferred as boolYou must assign a value when using `var`, since the compiler needs something to infer the type from. `var x;` alone will not compile — the compiler has no way to know what type x should be.
A common style question: when should you use var versus an explicit type? Many teams follow a simple rule — use var when the type is already obvious from the right-hand side of the assignment, and an explicit type when it genuinely improves readability.
var Reads Clearly Here
var customer = new Customer();var name = "Alex";var total = 19.99;Explicit Type Reads More Clearly Here
int result = CalculateScore(data); // what does this method return? clearer with the type shownDefault Values
Fields (variables belonging to a class, covered later) are automatically given a sensible default value if you don't explicitly initialize them — but local variables inside a method are not, and must always be assigned before use.
| Type | Default Value |
|---|---|
| int, double, and other numeric types | 0 |
| bool | false |
| string (and other reference types) | null |
| char | '\0' (the null character) |
Multiple Declaration
Several variables of the same type can be declared together on one line, separated by commas — useful for tightly related values, though most style guides recommend one variable per line for anything beyond the simplest cases.
int x = 1, y = 2, z = 3;Common Beginner Mistakes
int count = 5;count = "five"; // Error: cannot convert string to intC# requires local variables to be "definitely assigned" before use — the compiler will refuse to build otherwise, catching what would be a runtime bug in many other languages.
var overload_result_ratio = ComputeX(); tells a reader nothing about the type — reach for an explicit type whenever var would hide meaningful information.
int score; declares the variable but leaves it unassigned — attempting to read score before giving it a value is a compile error, not a runtime surprise.
FAQs
No — `var` is resolved to one single, fixed, concrete type at compile time based on the initializer expression. It is purely a syntax convenience for the developer; the compiled code is identical to writing the explicit type yourself.
No — once the compiler infers the type at the point of declaration, that variable behaves exactly like it was explicitly declared with that type for the rest of its scope.
None whatsoever — they compile to identical CIL; var is purely a source-code-level convenience with zero runtime cost or benefit.
It's a deliberate safety feature — reading an uninitialized variable in languages that allow it is a notorious source of unpredictable bugs, since the value could be garbage left over in memory from something unrelated.
Key Takeaways
- Variables store typed values in memory, and C# is statically typed — a variable's type cannot change after declaration.
- `var` infers the type at compile time from the initializer, but the resulting variable is exactly as strongly typed as if you'd written the type explicitly.
- Local variables must be assigned before use; class fields get automatic default values (0, false, or null depending on type).
- Naming conventions (camelCase for locals, PascalCase for types/methods) aren't enforced by the compiler, but following them makes your code instantly familiar to any other C# developer.
Summary
Variables are the fundamental containers every C# program builds on, and understanding var's true nature — compile-time inference, not dynamic typing — clears up one of the most common early misconceptions. Next, you'll learn about values that should never change at all: constants.