Variables
A variable is a named storage location for a value. In C# every variable has a type that's fixed when it's declared — a whole number, a piece of text, a true/false value — and the compiler makes sure you only store values of that type in it. This lesson covers declaring, assigning, var, constants and the rules the compiler enforces.
Declaring and assigning
Write the type, then the name, and optionally an initial value with =:
string name = "Priya"; int age = 31; double height = 1.68; bool isMember = true; Console.WriteLine($"{name} is {age}, {height} m tall. Member: {isMember}");
Priya is 31, 1.68 m tall. Member: True
Notice that a bool prints as True with a capital letter. You can also declare first and assign later, and change a variable's value as often as you like:
int score; score = 10; Console.WriteLine(score); score = score + 5; Console.WriteLine(score); score += 20; // shorthand for score = score + 20 Console.WriteLine(score);
10 15 35
Types are fixed
Once declared, a variable keeps its type. Assigning a value of the wrong type is a compile-time error, so mistakes are caught before the program ever runs:
int quantity = 3; quantity = "three";
Program.cs(2,12): error CS0029: Cannot implicitly convert type 'string' to 'int'
var: let the compiler infer the type
With var the compiler works out the type from the value on the right. The variable is still strongly typed — var just saves you writing the type twice:
var city = "Lisbon"; // string var population = 545_000; // int var ratio = 0.75; // double Console.WriteLine(city.GetType().Name); Console.WriteLine(population.GetType().Name); Console.WriteLine(ratio.GetType().Name);
String Int32 Double
Int32 and Double are the .NET names behind the C# keywords int and double. Because the type comes from the initial value, var needs one: var x; doesn't compile.
Use var when the type is obvious from the right-hand side (var list = new List<string>();), and write the type out when it helps the reader.
Use before assignment
C# won't let you read a local variable before it has definitely been given a value:
int total; Console.WriteLine(total);
Program.cs(2,19): error CS0165: Use of unassigned local variable 'total'
This rule (definite assignment) removes a whole class of bugs where a program reads leftover garbage from memory.
Constants
A const is a value fixed at compile time that can never change. Trying to modify one is an error:
const double VatRate = 0.2; const int DaysPerWeek = 7; double net = 50; Console.WriteLine($"Gross: {net * (1 + VatRate)}"); Console.WriteLine($"Hours per week: {DaysPerWeek * 24}");
Gross: 60 Hours per week: 168
Constants make "magic numbers" readable and keep them in one place. Only simple values — numbers, bool, char and string — can be const; for other values you'll use readonly fields (lesson 34).
Several variables at once
You can declare several variables of the same type in one statement, and use a tuple to assign or swap several at once:
int x = 1, y = 2, z = 3; Console.WriteLine($"{x} {y} {z}"); (x, y) = (y, x); // swap Console.WriteLine($"{x} {y}"); var (width, depth) = (4.5, 2.0); Console.WriteLine(width * depth);
1 2 3 2 1 9
Scope
A variable exists only inside the block where it's declared. Code outside the braces can't see it, and you can't declare two variables with the same name in overlapping scopes:
int count = 1; if (count > 0) { string message = "positive"; int count = 2; } Console.WriteLine(message);
Program.cs(5,9): error CS0136: A local or parameter named 'count' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter Program.cs(7,19): error CS0103: The name 'message' does not exist in the current context
Try it yourself
Declare variables for a product name, a price and a quantity, then print the total cost.
4 x Notebook = 9.96