Beginner · Getting started with C# and .NET · topic 4 of 43 · 30 min
Types and variables
Explanation
What is a variable?
A variable is a name for a place in memory that holds a value. You declare it by writing its type and its name, and usually give it a first value. Giving the first value is called initialising.
int age = 21;
string name = "Asha";
age = 22; // change the value
Console.WriteLine($"{name} is {age}");Static typing: why types matter
C# is statically typed. That means every variable's type is fixed when you write the code, and the compiler checks every use. If you try to put text into an int, the build fails before anyone runs the program. This catches many bugs early, which is one reason companies like C# for large systems.
int count = 10;
count = "ten"; // error CS0029: Cannot implicitly convert type 'string' to 'int'The common built-in types
| Type | Holds | Example |
|---|---|---|
| int | Whole numbers, about -2.1 billion to +2.1 billion (32 bits) | int marks = 87; |
| long | Very large whole numbers (64 bits) | long population = 1_400_000_000L; |
| double | Numbers with decimals, about 15 to 17 digits; fast but not exact | double distanceKm = 12.7; |
| float | Smaller, less precise decimals; needs f at the end | float speed = 3.5f; |
| decimal | Exact decimal numbers, 28 to 29 digits; for money; needs m at the end | decimal price = 499.99m; |
| bool | true or false | bool isPaid = true; |
| char | One character, in single quotes | char grade = 'A'; |
| string | Text, in double quotes | string city = "Chennai"; |
double versus decimal: money needs decimal
double stores numbers in binary (base 2). Many simple decimals such as 0.1 cannot be stored exactly in binary, just as 1/3 cannot be written exactly in decimal. Tiny errors appear. decimal stores numbers in base 10, so 0.1 is exact. For rupees, GST and bank balances, always use decimal.
double a = 0.1 + 0.2;
decimal b = 0.1m + 0.2m;
Console.WriteLine(a);
Console.WriteLine(b);var: let the compiler infer the type
var tells the compiler: "work out the type from the value on the right". The type is still fixed forever; var is not like JavaScript's let. You must give a value on the same line.
var total = 450; // int
var city = "Kochi"; // string
var rate = 0.18m; // decimal
// var x; // error: implicitly-typed variables must be initialized
// total = "big"; // error: total is an intconst: values that never change
const decimal GstRate = 0.18m;
const int DaysInWeek = 7;
// GstRate = 0.12m; // error: cannot assign to a constNames and rules
- Names may use letters, digits and _, but cannot start with a digit: total2 is fine, 2total is not.
- Names are case-sensitive: total and Total are different variables.
- Local variables use camelCase (monthlyRent). Types, methods and constants use PascalCase (GstRate).
- You cannot use a variable before it has a value: error CS0165, use of unassigned local variable.
Common mistakes and fixes
- Using double for money: switch to decimal and add m to literals.
- Using single quotes for text: 'Hello' is an error; use "Hello". Single quotes are only for one char.
- Declaring the same name twice in one block: error CS0128. Reuse the variable without the type: count = 5;
- Expecting int to hold 5 billion: it overflows. Use long for large counts like phone numbers stored as numbers (better still, store phone numbers as strings).
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Types and variables · 1/7
In this lesson you will store values in variables and choose the right type for each one.
Prefer a video by a teacher? Find free videos on “C# data types variables int double decimal string var const tutorial” on YouTube ↗
In real life: A student record at a coaching centre
A coaching centre in Kota keeps a few details for each student. Each detail gets the right type: the roll number is an int, the fee is decimal because it is money, the attendance percentage is a double, and whether the fee is paid is a bool.
int rollNo = 1042;
string name = "Meena Iyer";
char section = 'B';
decimal feePaid = 45_000.00m;
double attendance = 92.5;
bool scholarship = false;
Console.WriteLine($"{rollNo} {name} ({section})");
Console.WriteLine($"Fee paid: {feePaid}, attendance: {attendance}%, scholarship: {scholarship}");Practice (0/4 done)
Which type is best for storing a product price in rupees, like 1299.50?
Which line does NOT compile?
var total = 10; total = 2.5; What happens?
Write a program for a mobile recharge shop that stores: the customer's name, the mobile number (as a string), the plan price (money), the validity in days and whether it is an unlimited-calls plan. Print them all in two neat lines.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Operators, conversions and parsing inputGetting started with C# and .NET · same module
- Installing .NET and using the dotnet CLIGetting started with C# and .NET · same module
- Variables and primitive typesJava Programming (Core to Spring Boot) · Getting started with Java
- Variables, types and constantsC++ Programming (modern C++ and DSA) · First steps: compiling, output, variables and input
- Variables, basic types and zero valuesGo Programming (backend and cloud) · Getting started with Go
- Variables: let, const and varJavaScript Programming (language in depth) · First steps: values, variables and operators
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What does Console.WriteLine(0.1m + 0.2m); print?
Answer: 0.3
decimal adds decimals exactly, so the result is 0.3.
Which type holds true or false?
Answer: bool
bool has exactly two values: true and false.
What is wrong with: var x;
Answer: var needs a value on the same line so the compiler can infer the type
The compiler infers the type from the value, so var must be initialised.
Which is the correct way to write a char?
Answer: 'A'
A char is one character in single quotes.
const int Max = 10; Max = 20; What happens?
Answer: Compile error: a const cannot be changed
A const value is fixed at compile time and cannot be assigned again.
Roughly what is the largest value an int can hold?
Answer: About 2.1 billion
int is 32 bits: up to 2,147,483,647. For more, use long.
Which type should hold true or false?Related
What is in an int variable declared inside main with int n; and no value?Related
Answer: Garbage: reading it is undefined behaviour
Local variables are not set to zero automatically. Always initialise them.
Which type is another name for int32 and holds one Unicode character?Related
Answer: rune
rune is an alias for int32 and represents a Unicode code point.
if (true) { let a = 1; } console.log(a); What happens?Related
Answer: ReferenceError
let is block-scoped, so a does not exist outside the braces.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 1 more topic in “Getting started with C# and .NET” before its exam: Operators, conversions and parsing input.
- Module 1 exam: Getting started with C# and .NET · 13 questions · 20 min, without help. 5 topics of this module still to finish first.
- Then the next module, Decisions, loops and methods. 43 topics left in the course before the final exam.
← Previous: Your first program: output, input and the Main method