.NET Academy

Variables and types

Store values in named variables and pick the right type for each kind of data.

12 min read

You will learn

  • Declare and assign variables
  • Choose between the built-in types int, double, decimal, bool, char and string
  • Use var and const correctly
  • Convert between types safely

What is a variable?

A variable is a named box that holds a value. You give it a type (what kind of value can go in the box) and a name (so you can refer to it later):

int age = 36;
//│    │     └── the value
//│    └──────── the name
//└───────────── the type

You can change what's in the box later — but only to another value of the same type:

int age = 36;
age = 37;          // ✅ fine
age = age + 1;     // ✅ now 38
age = "old";       // ❌ compile error: a string is not an int

C# is statically typed

Every variable's type is fixed when the code is compiled. The compiler catches type mistakes before your program ever runs — one of the big reasons C# code tends to be reliable.

The built-in types you'll use most

TypeHoldsExample
intWhole numbers (±2.1 billion)int score = 42;
longVery large whole numberslong views = 8_000_000_000;
doubleDecimal numbers, fast but approximatedouble height = 1.65;
decimalExact decimal numbers — use for moneydecimal price = 19.99m;
booltrue or falsebool isAdmin = false;
charA single character, in single quoteschar grade = 'A';
stringText, in double quotesstring name = "Ada";

Notice the m suffix on 19.99m. Without it, 19.99 is a double, and C# won't silently turn it into a decimal.

Never use double for money

0.1 + 0.2 as double gives 0.30000000000000004. As decimal it gives exactly 0.3. Prices, balances and invoices should always be decimal.

Naming rules

  • Use camelCase for local variables: firstName, totalPrice.
  • Names can contain letters, digits and _, but can't start with a digit.
  • Names are case-sensitive: age and Age are different variables.
  • Pick names that describe the value: daysUntilDeadline beats d.

var — let the compiler infer the type

When the type is obvious from the right-hand side, you can write var:

var city = "Casablanca";   // string
var year = 2026;           // int
var ratio = 0.75;          // double

The variable still has a fixed type — var just saves you from typing it. You can't write var x; without a value, because the compiler would have nothing to infer from.

const — values that never change

const int MaxLoginAttempts = 5;
const double Pi = 3.14159;
 
MaxLoginAttempts = 6;  // ❌ compile error

Use const for fixed values known at compile time. Constants are conventionally named in PascalCase.

Converting between types

Implicit conversions happen automatically when no data can be lost:

int whole = 10;
double d = whole;      // ✅ 10.0 — every int fits in a double

Explicit conversions (casts) are required when data might be lost:

double price = 9.99;
int rounded = (int)price;   // 9 — the .99 is cut off, not rounded!

Parsing turns text into a number:

int a = int.Parse("123");            // 123
int b = int.Parse("hello");          // 💥 throws FormatException at runtime
 
if (int.TryParse("hello", out int c))
    Console.WriteLine(c);
else
    Console.WriteLine("Not a number"); // ✅ safe: no exception

Tip

Prefer TryParse whenever the text comes from a user or a file — you can't trust it to be a valid number.

Try it

Run this, then experiment: change "42" to "forty-two", or remove the (int) cast and read the compiler error.

Program.cs
Loading editor…

C# runtime not loaded

Putting values into strings

String interpolation — a $ before the string, and expressions in {braces} — is the cleanest way to build text:

string name = "Ada";
int age = 36;
 
Console.WriteLine($"{name} is {age} years old.");
// Ada is 36 years old.
 
Console.WriteLine($"Next year she'll be {age + 1}.");
// Next year she'll be 37.

Key takeaways

  • A variable = type + name + value, and its type never changes.
  • int for whole numbers, double for measurements, decimal for money, bool, char, string.
  • var infers the type; const makes a value unchangeable.
  • Widening conversions are implicit; narrowing ones need a cast; text needs Parse/TryParse.

Exercise

Declare three variables — name = "Ada", age = 36 and height = 1.65 — using appropriate types. Then print exactly: Ada is 36 years old and 1.65 m tall.

Program.cs
Loading editor…

C# runtime not loaded

Hint 1

name is text → string. age is a whole number → int. height has a decimal point → double.

Hint 2

Put a $ before the string and wrap variables in braces: $"{name} is ..."

Show solution
string name = "Ada";
int age = 36;
double height = 1.65;

Console.WriteLine($"{name} is {age} years old and {height} m tall.");

Quiz

4 questions · 3 correct to pass
  1. 1.Which type should you use to store a product price like 19.99 in a shopping app?

  2. 2.What is the type of x in `var x = 10;`?

  3. 3.What happens when you compile `int count = "5";`?

  4. 4.Which line will NOT compile?

To complete this lesson

  • ○ Solve the exercise
  • ○ Pass the quiz (3/4 correct)