C# Variables
A variable is a named storage location for a value. C# is statically typed: every variable has a type that is fixed when it is declared, and the compiler refuses to store a value of the wrong type in it.
Declaring variables
The basic form is type name = value;.
using System;
string city = "Lisbon";
int population = 545000;
double temperature = 21.5;
bool isCapital = true;
char grade = 'A';
Console.WriteLine(city);
Console.WriteLine(population);
Console.WriteLine(temperature);
Console.WriteLine(isCapital);
Console.WriteLine(grade);Lisbon
545000
21.5
True
A
| Type | Stores | Example |
|---|---|---|
int |
Whole numbers | 42 |
double |
Floating-point numbers | 3.14 |
char |
A single character (single quotes) | 'Z' |
string |
Text (double quotes) | "Hello" |
bool |
true or false |
true |
Declare now, assign later
You can declare a variable without a value and assign it afterwards. You can also change a variable's value at any time — the new value simply replaces the old one.
using System;
int score;
score = 10;
Console.WriteLine(score);
score = score + 5;
Console.WriteLine(score);
score = 99;
Console.WriteLine(score);10
15
99
C# enforces definite assignment: reading a local variable before it has been given a value is a compile-time error, so you can never accidentally use garbage memory.
int total;
Console.WriteLine(total); // error CS0165: Use of unassigned local variable 'total'Implicit typing with var
When the type is obvious from the right-hand side, you can write var and let the compiler infer it. The variable is still statically typed — var is just shorthand.
using System;
var count = 3; // int
var price = 9.99; // double
var title = "Notebook"; // string
Console.WriteLine(count.GetType().Name);
Console.WriteLine(price.GetType().Name);
Console.WriteLine(title.GetType().Name);Int32
Double
String
int, double and string are C# keywords that alias the .NET types System.Int32, System.Double and System.String.
Tip: Use
varwhen the type is obvious (var list = new List<int>();) and an explicit type when it helps the reader.
Multiple variables and naming rules
Several variables of the same type can be declared in one statement:
using System;
int x = 5, y = 6, z = 50;
Console.WriteLine(x + y + z);
int a, b, c;
a = b = c = 7;
Console.WriteLine(a + b + c);61
21
Rules for identifiers:
- They may contain letters, digits and underscores, but must not start with a digit.
- They are case-sensitive (
totalandTotalare different). - Reserved keywords like
intorclasscannot be used — unless prefixed with@, as in@class. - By convention local variables use camelCase:
firstName,itemCount.
Test yourself
Which declaration is valid C#?
- int 2count = 2;
- string name = 'Bob';
- double price = 4.5;
- bool ok = "true";
What type does the compiler infer for var n = 10;?
- double
- int
- long
- object
What happens if you read a local variable that was never assigned?
- It contains 0
- It contains null
- A compile-time error
- A runtime exception