- Declare a variable and assign a value to it
- Choose correctly between
int,double,decimal,bool,char,stringandvar - Convert between types with casts such as
(double)and withint.Parse - Use string interpolation, format specifiers and string methods
In a game, the player has a name, a score, lives left and a level. The program has to keep this information somewhere and change it as the game goes on. That is what variables are for. In C#, every variable has a type that decides what kind of value it can hold.
Variables
To declare a variable, write its type first, then its name, and assign a value with the = sign. Later you can give the variable a new value, but only of the same type. Names usually start with a lowercase letter, and each following word starts with a capital: playerName, livesLeft.
string playerName = "Leyla";
int score = 0;
int livesLeft = 3;
bool isGameOver = false;
score = score + 50;
score += 25;
livesLeft--;
Console.WriteLine(playerName);
Console.WriteLine(score);
Console.WriteLine(livesLeft);
Console.WriteLine(isGameOver);Leyla 75 2 False
score += 25is short forscore = score + 25; there are also-=,*=and/=.livesLeft--decreases the value by 1, and++increases it by 1.- A
boolvalue is printed with a capital letter,TrueorFalse, but written in lowercase in code:true,false.
Basic types
| Type | What it holds | Example |
|---|---|---|
int | whole numbers (up to about ±2.1 billion) | int age = 12; |
long | very large whole numbers | long views = 3_000_000_000; |
double | fractional numbers (measurements, science) | double height = 1.52; |
decimal | money and exact decimal calculations | decimal price = 4.99m; |
bool | a logical value: true or false | bool isOpen = true; |
char | one character, in single quotes | char grade = 'A'; |
string | text, in double quotes | string city = "Baku"; |
`var` and `const`
When the type is obvious from the right-hand side, you can write var instead — the compiler works out the type itself. This does not mean the variable has no type: after var city = "Baku";, city stays a string forever. For values that must never change, use const.
var city = "Baku";
var year = 2026;
var price = 2.5m;
const int DaysInWeek = 7;
Console.WriteLine(city.GetType().Name);
Console.WriteLine(year.GetType().Name);
Console.WriteLine(price.GetType().Name);
Console.WriteLine(DaysInWeek * 4);String Int32 Decimal 28
GetType().Name shows the type's name in .NET: int is really a short name for Int32, and string for String. If you try city = 5;, the compiler reports error CS0029: an int cannot be converted to a string. And DaysInWeek = 8; is not allowed at all, because it is a constant.
Numbers and conversions
You already know that 7 / 2 gives 3. If you need a fractional result, convert one of the numbers to double: (double)7 / 2. This is called a cast. In the other direction, (int)3.99 drops the fractional part and gives 3 — it does not round! To turn text into a number, use int.Parse; to turn a number into text, use ToString().
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
int apples = 7;
int friends = 2;
Console.WriteLine(apples / friends);
Console.WriteLine((double)apples / friends);
Console.WriteLine((int)3.99);
Console.WriteLine(Math.Round(3.99));
int year = int.Parse("2026");
Console.WriteLine(year + 1);
Console.WriteLine(year.ToString() + "!");3 3.5 3 4 2027 2026!
Strings and interpolation
Building text with + quickly gets tiring. String interpolation is easier: put $ before the string and write variables and expressions straight into the text inside curly braces. After a colon inside the braces you can add a format: F2 means two digits after the decimal separator, N0 a whole number with thousands separators.
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
string name = "Murad";
int score = 95;
decimal price = 4.5m;
int views = 1234567;
Console.WriteLine("Hi, " + name + "!");
Console.WriteLine($"{name} scored {score} points.");
Console.WriteLine($"Next time: {score + 5}");
Console.WriteLine($"3 tickets: {price * 3:F2} AZN");
Console.WriteLine($"Views: {views:N0}");Hi, Murad! Murad scored 95 points. Next time: 100 3 tickets: 13.50 AZN Views: 1,234,567
A string is an object too, with useful properties and methods. Note that strings are immutable: methods like ToUpper() do not change the original but return a new string. Characters are accessed by index, and counting starts at zero.
string city = " Baku ";
string clean = city.Trim();
Console.WriteLine(clean.Length);
Console.WriteLine(clean.ToUpper());
Console.WriteLine(clean.Contains("ak"));
Console.WriteLine(clean.Replace("Baku", "Ganja"));
Console.WriteLine(clean[0]);
Console.WriteLine($"[{city}]");4 BAKU True Ganja B [ Baku ]
Trim() did not change the original city string.Key points
- A variable has a type, a name and a value:
int score = 0;. - Use
intfor whole numbers,doublefor fractions,decimalfor money andstringfor text. varlets the compiler infer the type, but the type never changes afterwards;constis a value that cannot change.(double)andint.Parseconvert types;(int)3.99does not round — it gives3.- Interpolation with
$is the easiest way to build text;{x:F2}shows two decimal places. - Strings are immutable:
ToUpper(),Trim()andReplace()return a new string.
Check yourself
10 questions. Every correct answer earns XP.