Programs work with data: a user's name, the number of items in a basket, a price, whether someone is logged in. A variable is a named place to store a value so you can use and change it later.
C# is statically typed, so every variable has a type that decides what kind of value it can hold and what you can do with it. You can't accidentally put text into a variable meant for a number: the compiler stops you. That might feel strict at first, but it catches a whole category of bugs before your program ever runs, and it lets your editor offer accurate suggestions as you type.
In this lesson you'll declare variables, meet the built-in types you'll use every day, let the compiler infer types with var, make values that never change with const, and convert safely between types, including turning text typed by a user into a number.
Declaring variables
int age = 30; // type, name, value
string name = "Ada";
age = 31; // change the value later
int count; // declare now...
count = 5; // ...assign before use- A local variable must be assigned before it's read, or the compiler reports error CS0165.
- Names start with a letter or underscore, contain letters, digits and underscores, and use camelCase:
totalPrice,isLoggedIn. - Choose descriptive names;
basketTotaltells a reader far more thanbt.
Built-in types
| Type | Holds | Example |
|---|---|---|
int | Whole numbers up to about 2.1 billion | int stock = 120; |
long | Very large whole numbers | long views = 9_000_000_000; |
double | Decimal numbers (fast, approximate) | double distance = 12.5; |
float | Smaller, less precise decimals, used in Unity | float speed = 3.5f; |
decimal | Exact decimals for money | decimal price = 19.99m; |
bool | true or false | bool inStock = true; |
char | One character, in single quotes | char grade = 'A'; |
string | Text, in double quotes | string city = "Leeds"; |
Suffixes tell C# the literal's type: f for float, m for decimal, L for long. Underscores in numbers like 1_000_000 are just for readability.
var, const and conversions
var lets the compiler work out the type from the value: var total = 0; is an int. The type is still fixed; var only saves typing.
const declares a value that can never change: const int MaxItems = 10;.
Converting between types:
- Implicit conversions happen automatically when nothing can be lost:
inttolongordouble. - Explicit casts are needed when data could be lost:
(int)9.8gives9, cutting off the fraction. - Parsing turns text into numbers:
int.Parse("42"), or the saferint.TryParse(text, out int n), which returnsfalseinstead of crashing when the text isn't a number.
Type ranges, literals and default values
Every numeric type has a fixed size, so it has a smallest and largest value. You can ask for them with MinValue and MaxValue:
Console.WriteLine(int.MaxValue); // 2147483647
Console.WriteLine(int.MinValue); // -2147483648
Console.WriteLine(long.MaxValue); // 9223372036854775807Whole numbers can also be written in hexadecimal with 0x or binary with 0b. 0xFF is 255 and 0b1010 is 10, which is handy for colours and bit flags.
Each type also has a default value: 0 for numbers, false for bool and null for string. You get it with the default keyword, so default(int) is 0. Fields in a class start at their default value automatically, but local variables don't, which is why the compiler insists you assign them before use.
The short type names are aliases for .NET types: int is System.Int32, long is System.Int64, double is System.Double and string is System.String. You'll see both forms in documentation, and they mean exactly the same thing.
C# Basics Syntax
Variables and types
int count = 3;
double ratio = 0.75;
decimal price = 9.99m;
float speed = 2.5f;
bool done = false;
char letter = 'x';
string text = "hello";
var inferred = 42; // int
const double Pi = 3.14159;
int whole = (int)7.9; // 7
int parsed = int.Parse("12");
bool ok = int.TryParse("abc", out int n); // false, n is 0C# Basics Summary
- Variables have a type, a name and a value; locals must be assigned before use.
- int, long, double, float, decimal, bool, char and string are the everyday types.
- var infers the type from the value; the type is still fixed.
- const declares a value that never changes.
- Casts convert explicitly; int.TryParse converts text safely.
C# Basics Examples
Each example shows the code, the output it produces and what each part does.
A product record in variables
string product = "Desk lamp";
decimal price = 24.99m;
int stock = 12;
bool onSale = false;
char sizeCode = 'M';
Console.WriteLine(product);
Console.WriteLine(price);
Console.WriteLine(stock);
Console.WriteLine(onSale);
Console.WriteLine(sizeCode);
stock = stock - 3;
Console.WriteLine("Stock after sales: " + stock);Desk lamp
24.99
12
False
M
Stock after sales: 9Line-by-line explanation
- Line 2The m suffix makes 24.99 a decimal, the right type for money.
- Line 10C# prints booleans as True and False, with capital letters.
- Line 13A variable can be given a new value of the same type.
- Line 14+ joins a string and a number into one string.
var, const and casting
var quantity = 3;
var unitPrice = 2.5;
const int MaxPerOrder = 5;
double total = quantity * unitPrice;
Console.WriteLine(total);
int rounded = (int)total;
Console.WriteLine(rounded);
long big = quantity;
Console.WriteLine(big + MaxPerOrder);
Console.WriteLine(quantity.GetType().Name);
Console.WriteLine(unitPrice.GetType().Name);7.5
7
8
Int32
DoubleLine-by-line explanation
- Lines 1 to 2var infers int from 3 and double from 2.5.
- Line 3A const value is fixed when the program is compiled.
- Line 8The cast cuts off the fraction; it doesn't round.
- Line 11int converts to long automatically, because nothing can be lost.
- Lines 14 to 15GetType shows the real .NET type names behind int and double.
Parsing text safely
string[] inputs = { "42", "seven", " 15 ", "" };
foreach (string text in inputs)
{
if (int.TryParse(text, out int number))
{
Console.WriteLine($"Got {number}, doubled is {number * 2}");
}
else
{
Console.WriteLine($"'{text}' is not a whole number");
}
}
Console.WriteLine(0.1 + 0.2 == 0.3);
Console.WriteLine(0.1m + 0.2m == 0.3m);Got 42, doubled is 84
'seven' is not a whole number
Got 15, doubled is 30
'' is not a whole number
False
TrueLine-by-line explanation
- Line 5TryParse returns true or false and puts the number in the out variable when it works.
- Line 7$"..." is an interpolated string; values in braces are inserted.
- Line 5Leading and trailing spaces are allowed, so " 15 " parses.
- Line 15double arithmetic is approximate, so the comparison is False.
- Line 16decimal arithmetic is exact, so it's True.
Common C# Basics Mistakes
Assigning the wrong type
int age = "30"; // error CS0029: cannot convert string to intint age = int.Parse("30");Forgetting the m suffix on decimals
decimal price = 9.99; // error CS0664: use the 'M' suffixdecimal price = 9.99m;int.Parse on user input
int qty = int.Parse(Console.ReadLine()); // crashes on "two" or an empty lineif (!int.TryParse(Console.ReadLine(), out int qty))
{
qty = 1;
}C# Basics in Real Projects
Types in business code
Shopping carts, invoices and banking systems store amounts as decimal so totals are accurate to the penny. Counts and ids use int or long, flags use bool, and anything users type arrives as a string that's parsed with TryParse. Game code in Unity uses float for positions and speeds, because graphics hardware works with floats.
C# Basics FAQ
When should I use var in C#?
Use var when the type is obvious from the right-hand side, such as var names = new List<string>();, because repeating the type adds nothing. Write the type out when it isn't obvious, for example int count = GetCount();. Either way the variable gets a fixed type at compile time, so var never makes C# dynamic.
What is the difference between double and decimal?
double stores numbers in binary floating point, so it's fast and covers a huge range but can't represent values like 0.1 exactly. decimal stores numbers in base 10 with up to 28 or 29 significant digits, so money adds up exactly. Use decimal (with the m suffix) for prices and double for measurements.
What is the difference between string and String in C#?
There's no difference: string is the C# keyword alias for the System.String class. The same goes for int and System.Int32. Most style guides use the lowercase keywords for declarations, such as string name.
How do I convert a string to an int in C#?
Use int.TryParse(text, out int number) when the text might not be valid, for example when a user typed it. It returns false instead of throwing an exception. Use int.Parse(text) only when you're sure the text is a valid number, because it throws a FormatException otherwise.
What happens if I go past int.MaxValue?
By default the value wraps around silently, so int.MaxValue + 1 at run time becomes -2147483648. Wrap the calculation in checked(...) to get an OverflowException instead, or use long when your numbers can grow beyond about 2.1 billion.
C# Basics Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the declaration to store a price exactly.
price = 4.50m;
What does this print?
int x = (int)8.9;
Console.WriteLine(x);
What type does var n = 5.0; give n?
What does this print?
bool ok = int.TryParse("12a", out int n);
Console.WriteLine($"{ok} {n}");
Why does double total = 0.1 + 0.2; not equal 0.3 exactly?
C# Basics Quiz
5 questions to check what you learned.
Which type holds true or false?
- bool
- int
- string
- char
What does const mean?
- The variable is private
- The value is fixed and can never change
- The variable can hold any type
- The value is calculated later
Which literal is a char?
- "A"
- A
- 'A'
A
Does var make a variable dynamically typed?
- Yes, it can hold any type later
- Only for strings
- No, the compiler infers one fixed type from the value
- Only inside methods
Which method converts text to an int without throwing on invalid input?
- int.Parse
- Convert.ToInt32
- (int)text
- int.TryParse