the short answer
A variable in C# is a named box that holds one value, and its type says what kind of value fits inside. string name = "Sam"; makes a string box called name that holds Sam. The types you will use most are int for whole numbers, double for decimals, decimal for money, bool for true or false and string for text. A variable keeps its type for good.
A variable in C# is a named box that holds one value. You write the type of the box, its name, and the value to put in it. From then on, using the name gives you the value back:
using System;
string name = "Sam";
int age = 9;
double height = 1.32;
bool likesCats = true;
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(height);
Console.WriteLine(likesCats);Sam
9
1.32
TrueThe type is the part that makes C# different from languages like Python or JavaScript. It says what kind of value fits in the box, and C# checks it before your program runs. This guide covers the types you will use most, how to change a variable, when to let C# work out the type with var, how to name things, and the errors you will meet along the way.
Every example runs in your browser. Each one starts with using System;, which gives you Console.WriteLine for printing. The examples are written as top-level statements, a short style that lets a small C# program skip the class and Main method you will see in bigger programs.
Making a variable
int age = 9; has five parts:
intis the type: this box holds whole numbers.ageis the name on the label.=means put this value in the box. It is not a question about whether two things are equal.9is the value.;ends the instruction.
Making the box is called declaring the variable. Putting a value in it is called assigning. You can do both at once, as above, or declare first and assign later. Doing both at once is the safer habit, as the mistakes section shows.
The types you will use most
intholds whole numbers, like 9 or -40.doubleholds numbers with a decimal point, like 1.32.decimalalso holds decimals, but exactly. It is the one to use for money.boolholds true or false. When printed, it shows as True or False with a capital letter.stringholds text, written in double quotes.charholds a single character, written in single quotes, like'A'.
Whole numbers and division
When both numbers in a division are int, C# keeps the whole-number part and throws the rest away:
using System;
Console.WriteLine(7 / 2);
Console.WriteLine(7 / 2.0);3
3.5Make either number a decimal value, like 2.0, and you get the full answer.
decimal for money
A double stores numbers in binary, so most decimals are kept as a very close approximation. That is fine for measurements, but money needs to add up exactly. Compare the two:
using System;
Console.WriteLine(0.1 + 0.2);
Console.WriteLine(0.1m + 0.2m);0.30000000000000004
0.3The m at the end of a number makes it a decimal. You need it whenever you write a decimal value in your code:
using System;
decimal price = 4.99m;
int quantity = 3;
Console.WriteLine(price * quantity);14.97Changing a variable
A variable can be given a new value at any time. Leave out the type, because the box already exists:
using System;
int score = 10;
score = score + 5;
score += 1;
Console.WriteLine(score);16score = score + 5 reads the current value, adds 5 and puts the result back. score += 1 is a shorter way to write the same kind of thing. What cannot change is the type: an int box only ever holds whole numbers.
Letting C# work out the type with var
Instead of a type, you can write var. C# looks at the starting value and picks the type for you:
using System;
var city = "Leeds";
var visitors = 120;
Console.WriteLine($"{city} had {visitors} visitors");Leeds had 120 visitorsHere city becomes a string and visitors becomes an int. The $ before the quotes turns on string interpolation, which swaps each name in curly brackets for its value.
var does not make a box that holds anything. The type is fixed the moment the variable is made:
using System;
var city = "Leeds";
city = 5;line 4: CS0029: Cannot implicitly convert type 'int' to 'string'For the same reason, var needs a starting value. var total; on its own is an error, because there is nothing to work the type out from.
Values that never change: const
const makes a value that can never be changed. It suits things that are fixed by the rules of your program:
using System;
const int MaxLives = 3;
int lives = MaxLives;
lives = lives - 1;
Console.WriteLine($"{lives} of {MaxLives} lives left");2 of 3 lives leftTry to change MaxLives later and C# stops you before the program runs:
using System;
const int MaxLives = 3;
MaxLives = 4;line 4: CS0131: The left-hand side of an assignment must be a variable, property or indexerNaming variables
The rules C# enforces:
- Names use letters, digits and underscores, with no spaces.
- A name cannot start with a digit, so
2ndPlaceis not allowed. - A name cannot be a keyword that C# already uses, like
intorclass. - Capitals matter:
scoreandScoreare two different variables.
The habits most C# code follows:
- Variables are written in camelCase: a small first letter, then a capital at the start of each new word, like
playerName. - Constants usually start with a capital letter, like
MaxLives. - Names say what the value is.
totalPricetells the next reader far more thantdoes.
Common mistakes
Using a variable before it has a value
using System;
int total;
Console.WriteLine(total);line 4: CS0165: Use of unassigned local variable 'total'The box exists but is empty, and C# refuses to read an empty box. Give it a starting value, like int total = 0;.
Capital letters that do not match
using System;
string playerName = "Sam";
Console.WriteLine(playername);line 4: CS0103: The name 'playername' does not exist in the current contextTo C#, playerName and playername are different names, and only one of them was made.
Forgetting the m on a decimal
using System;
decimal price = 4.99;line 3: CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this typeWithout the m, 4.99 is a double, and C# will not quietly turn it into a decimal. The message even tells you the fix.
Making the same variable twice
using System;
int lives = 3;
int lives = 2;line 4: CS0128: A local variable or function named 'lives' is already defined in this scopeThe second line tries to make a new box with a name that is already taken. To change the value, leave out the type: lives = 2;.
Text in a number box
using System;
int age = "9";line 3: CS0029: Cannot implicitly convert type 'string' to 'int'The quotes make "9" text, even though it looks like a number. Take the quotes away and it is the number 9.
A short exercise
A café sells tea for £1.80 a cup. Make three variables: the customer’s name, the number of cups and the price of one cup, each with a sensible type. Then work out the total and print a line like this:
Ava owes £5.40 for 3 cupsTo try it out, open the playground from the button at the bottom of the page and choose C#.
One possible answer
using System;
string customer = "Ava";
int cups = 3;
decimal teaPrice = 1.80m;
decimal total = teaPrice * cups;
Console.WriteLine($"{customer} owes £{total} for {cups} cups");Ava owes £5.40 for 3 cupsThe price is a decimal because it is money, and the number of cups is an int because you cannot buy half a cup here. Multiplying a decimal by an int gives a decimal, so total is a decimal too.
Related reading
- Java’s main method explained. Classic C# programs start in a Main method that works the same way.
- TypeScript vs JavaScript, for how another language adds types to every variable.
Your next step
Variables are in every program you will ever write, so they are the place to start. Gwecode’s C# Level 1 begins with exactly this idea, a variable as a labelled box, then moves on to decisions, loops, arrays and functions of your own, one short lesson at a time. Its level check is a tiny quiz game you build yourself. Every lesson is free and runs in your browser. Create a free account to keep your progress, and start with the lesson below.
practise this · c# · lessonA variable is a labelled boxstart the lessonquestions
What is the difference between var and a type name?
None, once the code runs. var asks C# to work out the type from the starting value, so var age = 9; makes an int, exactly like int age = 9;. The variable keeps that type for good.
Should I use double or decimal?
Use decimal for money and anything that must add up exactly. Use double for measurements and science, where tiny rounding differences do not matter.
Why does C# say a variable is unassigned?
C# will not let you read a variable before a value has been put in it. Give it a starting value when you make it, such as int total = 0;.
Are C# variable names case-sensitive?
Yes. score and Score are two different names. Variables inside your code are usually written in camelCase, starting with a small letter, like playerName.
What does const do?
const makes a value that can never change, such as const int MaxLives = 3;. Trying to change it later is an error, which protects values that should stay fixed.
