BuildQuill
C# learning path
2 of 25
Lesson 2 of 25
Lesson 2Beginner15 min

C# Variables and Data Types

Learn why programs name values, how types prevent invalid operations, and how to choose types for text, counts, measurements, money, and state.

Before this lesson

  • How a C# program runs
  • Statements and Console.WriteLine

Declare, read, and update variables

Choose a type from the meaning of the data

Distinguish a variable, a literal, a constant, and var inference

The short answer

A variable is a named place for a value your program needs to remember. Its type defines the kind of value it can hold and which operations are valid, such as int for whole-number counts, decimal for base-10 money, string for text, and bool for true-or-false state.

01

Why values need names

A program could repeat the number 4.50 everywhere, but the number alone does not say whether it is a price, a tax rate, or a distance. It also becomes difficult to update consistently. A variable connects a meaningful name to a value so later instructions can use that value without rediscovering it.

In int quantity = 3;, int is the type, quantity is the name, and 3 is a literal value written directly in the code. The equals sign assigns the value on its right to the variable on its left. It does not ask whether the sides are equal; comparison comes later.

C#
using System;

class Program
{
  static void Main()
  {
      int unreadMessages = 2;
      Console.WriteLine(unreadMessages);

      unreadMessages = unreadMessages + 1;
      Console.WriteLine(unreadMessages);
  }
}

Expected output

2
3
02

Choose a type from what the value means

Types are not labels added only for the compiler. They document what a value represents and rule out operations that do not fit. A message can be joined with more text; a count can be added; a Boolean can decide whether code runs. C# checks those expectations before execution whenever it can.

Use int for ordinary whole-number counts and long when the range may be much larger. double is the normal choice for measurements and scientific calculations. decimal represents base-10 fractions more predictably and is commonly chosen for money; decimal literals use an m suffix. char holds one UTF-16 code unit in single quotes, while string holds text in double quotes.

MeaningUsual typeExample
Number of attendeesintint attendees = 42;
Very large file countlonglong files = 3_000_000_000L;
Temperature or measurementdoubledouble temperature = 21.6;
Price or account amountdecimaldecimal price = 19.99m;
True-or-false stateboolbool isOpen = true;
Textstringstring city = "Lahore";
03

Changing values, constants, and var

A variable can be assigned another compatible value. That change is useful for a score, balance, or current position. If a named value must not change, declare it with const. The compiler will then reject later assignments. Constants are useful for fixed rules inside the program, not for settings that users or administrators may need to change without rebuilding it.

The var keyword asks the compiler to infer a variable's type from its initial value. var total = 12.5m is still statically typed as decimal; it does not become a container for anything. Use var when the right side makes the type obvious, and spell out the type when doing so communicates important meaning.

C#
const decimal TaxRate = 0.15m;
decimal subtotal = 80m;
var tax = subtotal * TaxRate; // inferred as decimal
decimal total = subtotal + tax;

Good habits

  • Use camelCase for local variable names and PascalCase for constants in this course's style.
  • Prefer names such as remainingSeats over vague names such as number2.
  • Keep one meaning per variable; do not reuse total later to mean a percentage.
04

A practical order calculation

The following program stores facts about an order, derives a new value, and presents the result. Notice that total is not an independent fact: it is calculated from quantity and unitPrice. Keeping that relationship in code avoids manually synchronizing three values.

String interpolation begins with a dollar sign and places expressions inside braces. The :C format displays a number as currency using the environment's current culture. Formatting changes the displayed text, not the numeric value stored in total.

C#
using System;

class Program
{
  static void Main()
  {
      string item = "Water bottle";
      int quantity = 3;
      decimal unitPrice = 7.25m;
      decimal total = quantity * unitPrice;

      Console.WriteLine($"Item: {item}");
      Console.WriteLine($"Quantity: {quantity}");
      Console.WriteLine($"Total: {total:0.00}");
  }
}

Expected output

Item: Water bottle
Quantity: 3
Total: 21.75

Quick knowledge check

Answer before you reveal.

01Can an int variable later hold the text "three"?

No. Its declared type remains int. Convert or parse text into a number before assigning it.

02Does var make a variable dynamically typed?

No. The compiler infers one fixed type from the initializer and checks later uses normally.

Practice challenge

Now build it without copying.

Model a bus ticket purchase with variables for destination, ticket count, price per ticket, and whether the trip is direct. Calculate and print the total.

You are done when

  • Each variable uses a type that matches its meaning
  • The total is calculated rather than typed as a separate unexplained literal
  • The output is one readable interpolated summary

Stretch: Add a const service fee and include it once in the final total.

Open challenge in playground

Lesson checkpoint

One small step locks it in

Mark this lesson complete, then keep the momentum going.

Complete and continue

Clear up the details

Frequently asked questions

Why not use double for every number?

Different types communicate intent and have different ranges and representations. int models whole counts directly, while decimal avoids many base-10 rounding surprises in financial calculations.

Can a variable be declared without a value?

A local variable can be declared first, but C# requires it to be definitely assigned before it is read. Initializing near the declaration is usually clearer for beginners.

What is dynamic?

dynamic postpones many member and operation checks until runtime. It is useful for specific interop scenarios, but var or an explicit type is safer for ordinary code.