Variables and basic types
Course contents (16 lessons)
- Getting started
- Installing the .NET 10 SDK and checking it works
- Your first console app and top-level statements
- The building blocks
- Variables and basic types
- Working with strings and interpolation
- Reading input and writing output
- Making decisions and repeating work
- Conditionals and switch expressions
- Loops: for, while, do and foreach
- Collections and methods
- Arrays and List of T
- Writing your own methods
- Objects and classes
- Classes and objects
- Properties, encapsulation and object initialisers
- Handling null safely
- Errors and files
- Exceptions: try, catch, finally and throw
- Reading and writing files
- Final project: expense tracker
- Expense tracker, part 1: planning, model and storage
- Expense tracker, part 2: the menu and summaries
A variable is a named box
A variable holds a value while your program runs. You give it a name and a type. The type says what kind of value it can hold. C# checks types before the program starts, so many mistakes are caught early. That is one of the reasons I like the language.
The pattern is always the same: type, name, equals sign, value.
int age = 34;
string city = "Lahore";
bool isStudent = false;
The types you will use every day
| Type | Holds | Example |
|---|---|---|
int | Whole numbers up to about 2.1 billion | 42 |
long | Very large whole numbers | 9000000000L |
double | Decimal numbers, fast but slightly inexact | 3.14 |
decimal | Decimal numbers that stay exact, used for money | 19.99m |
bool | true or false | true |
char | One character | 'A' |
string | Text | "hello" |
Notice the m after the decimal and the L after the long. These suffixes tell the compiler which type you mean. Without the m, 19.99 is a double, and C# will refuse to put it into a decimal variable.
Why decimal for money
A double stores numbers in binary. Some decimal fractions, like 0.1, cannot be stored exactly in binary. The error is tiny, but it shows up. Run the example below and see for yourself.
double a = 0.1;
double b = 0.2;
Console.WriteLine(a + b == 0.3); // False
Console.WriteLine(a + b); // 0.30000000000000004
decimal c = 0.1m;
decimal d = 0.2m;
Console.WriteLine(c + d == 0.3m); // True
int items = 3;
decimal price = 19.99m;
decimal total = items * price;
Console.WriteLine($"Total: {total}"); // Total: 59.97
const double Pi = 3.14159;
var radius = 5; // the compiler picks int
Console.WriteLine(Pi * radius * radius);
Walking through it
The first block adds two doubles and compares the sum to 0.3. The answer is False, because the sum is really 0.30000000000000004. The second block uses decimal and gets True. For prices, taxes and balances, always use decimal. For measurements, scientific values and graphics, double is fine.
The const keyword makes a value that can never change. If you try to assign to Pi later, the compiler stops you. Constants are named in PascalCase by convention.
The var keyword tells the compiler to work out the type from the value on the right. var radius = 5; makes radius an int. It is not a loose type. The type is still fixed, you just did not write it. Use var when the type is obvious from the right side, and write the type out when it helps the reader.
The $"..." text is string interpolation. It lets you put variables inside text. We cover it in the next lesson.
Converting between types
C# converts automatically when nothing can be lost. An int fits into a long, so that works without extra code. Going the other way loses information, so you must ask for it with a cast:
double price = 9.99;
int rounded = (int)price; // 9, the decimal part is cut off, not rounded
int better = (int)Math.Round(price); // 10
Converting text to a number is a different job. Use int.Parse("42") or the safer int.TryParse, which we use in the input lesson.
Naming rules
Names can contain letters, digits and underscores but cannot start with a digit. Use camelCase for local variables (totalPrice) and PascalCase for constants and types. Choose names that say what the value means. d tells the reader nothing. daysUntilDue tells them everything.
Common mistakes
- Integer division.
7 / 2gives3, because both numbers are ints. Write7 / 2.0or7.0 / 2to get3.5. - Using double for money. It works until the day a total is off by a fraction of a cent.
- Using a variable before it has a value. The compiler refuses with "use of unassigned local variable".
- Forgetting the
msuffix on decimal literals.
Try it yourself
- Declare variables for a product: name (string), quantity (int), unit price (decimal), and whether it is in stock (bool). Print them.
- Compute the total price and print it.
- Print
7 / 2,7 / 2.0and7 % 2. Explain each result in a comment. The last one is the remainder operator. - Try to change a
constand read the compiler message.
double a = 0.1;
double b = 0.2;
Console.WriteLine(a + b == 0.3); // False
Console.WriteLine(a + b); // 0.30000000000000004
decimal c = 0.1m;
decimal d = 0.2m;
Console.WriteLine(c + d == 0.3m); // True
int items = 3;
decimal price = 19.99m;
decimal total = items * price;
Console.WriteLine($"Total: {total}"); // Total: 59.97
const double Pi = 3.14159;
var radius = 5; // the compiler picks int
Console.WriteLine(Pi * radius * radius);
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account