Skip to content

Beginner · Getting started with C# and .NET · topic 4 of 43 · 30 min

Types and variables

Explanation

A variable is a named box that holds a value, and in C# every box has a fixed type: int for whole numbers, double for measurements, decimal for money, bool for true/false, char for one character and string for text. var lets the compiler work out the type, but the type is still fixed. const makes a value that can never change.

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.

csharp
int age = 21;
string name = "Asha";
age = 22;              // change the value
Console.WriteLine($"{name} is {age}");
Shows Asha is 22. The type comes first, then the name, then = and the value.
Think of it like this: A variable is like a labelled steel dabba in the kitchen. The label is the name. A dabba made for rice (int) cannot suddenly hold oil (text). In C#, the label also says what may go inside, and the compiler checks this before the program even runs.

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.

csharp
int count = 10;
count = "ten";   // error CS0029: Cannot implicitly convert type 'string' to 'int'
The compiler stops you.

The common built-in types

TypeHoldsExample
intWhole numbers, about -2.1 billion to +2.1 billion (32 bits)int marks = 87;
longVery large whole numbers (64 bits)long population = 1_400_000_000L;
doubleNumbers with decimals, about 15 to 17 digits; fast but not exactdouble distanceKm = 12.7;
floatSmaller, less precise decimals; needs f at the endfloat speed = 3.5f;
decimalExact decimal numbers, 28 to 29 digits; for money; needs m at the enddecimal price = 499.99m;
booltrue or falsebool isPaid = true;
charOne character, in single quoteschar grade = 'A';
stringText, in double quotesstring city = "Chennai";
Tip: You can put underscores between digits to make big numbers readable, even in the Indian style: int oneLakh = 1_00_000; The compiler ignores the underscores.

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.

csharp
double a = 0.1 + 0.2;
decimal b = 0.1m + 0.2m;
Console.WriteLine(a);
Console.WriteLine(b);
Shows 0.30000000000000004, then 0.3.
Careful: decimal price = 99.5; does not compile (error CS0664). A number with a decimal point is a double by default. Add the m suffix: 99.5m. In the same way, float needs f: 3.5f.

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.

csharp
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 int
var is a shortcut, not a "any type" box.

const: values that never change

csharp
const decimal GstRate = 0.18m;
const int DaysInWeek = 7;
// GstRate = 0.12m;     // error: cannot assign to a const
A const value is fixed when you compile. Use it for true constants like rates and limits.

Names 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

Types and variables

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.

csharp
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}");
Shows 1042 Meena Iyer (B), then Fee paid: 45000.00, attendance: 92.5%, scholarship: False.

Practice (0/4 done)

Task 1 · Question

Which type is best for storing a product price in rupees, like 1299.50?

Task 2 · Question

Which line does NOT compile?

Task 3 · Question

var total = 10; total = 2.5; What happens?

Task 4 · Practice

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

Question 1

1.What does Console.WriteLine(0.1m + 0.2m); print?

Question 2

2.Which type holds true or false?

Question 3

3.What is wrong with: var x;

Question 4

4.Which is the correct way to write a char?

Question 5

5.const int Max = 10; Max = 20; What happens?

Question 6

6.Roughly what is the largest value an int can hold?

Read more (free)

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

Answer: boolean

boolean holds exactly true or false.

From Variables and primitive types

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.

From Variables, types and constants

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.

From Variables, basic types and zero values

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.

From Variables: let, const and var

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. 1 more topic in “Getting started with C# and .NET” before its exam: Operators, conversions and parsing input.
  2. Module 1 exam: Getting started with C# and .NET · 13 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. 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