Tutorials / C# for Beginners / Variables and basic types

Variables and basic types

13 min read csharp
Course contents (16 lessons)
  1. Getting started
  2. Installing the .NET 10 SDK and checking it works
  3. Your first console app and top-level statements
  4. The building blocks
  5. Variables and basic types
  6. Working with strings and interpolation
  7. Reading input and writing output
  8. Making decisions and repeating work
  9. Conditionals and switch expressions
  10. Loops: for, while, do and foreach
  11. Collections and methods
  12. Arrays and List of T
  13. Writing your own methods
  14. Objects and classes
  15. Classes and objects
  16. Properties, encapsulation and object initialisers
  17. Handling null safely
  18. Errors and files
  19. Exceptions: try, catch, finally and throw
  20. Reading and writing files
  21. Final project: expense tracker
  22. Expense tracker, part 1: planning, model and storage
  23. 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

TypeHoldsExample
intWhole numbers up to about 2.1 billion42
longVery large whole numbers9000000000L
doubleDecimal numbers, fast but slightly inexact3.14
decimalDecimal numbers that stay exact, used for money19.99m
booltrue or falsetrue
charOne character'A'
stringText"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 / 2 gives 3, because both numbers are ints. Write 7 / 2.0 or 7.0 / 2 to get 3.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 m suffix on decimal literals.

Try it yourself

  1. Declare variables for a product: name (string), quantity (int), unit price (decimal), and whether it is in stock (bool). Print them.
  2. Compute the total price and print it.
  3. Print 7 / 2, 7 / 2.0 and 7 % 2. Explain each result in a comment. The last one is the remainder operator.
  4. Try to change a const and read the compiler message.
csharp
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