Skip to main content

📝 Lesson 2.1: Variables and Data Types

Programs are useful because they remember and work with information. In this lesson you'll learn how C# stores data in variables and how types keep that data organized and safe.

🎯 Learning Objectives

By the end of this lesson, you will be able to:

  • Declare variables and assign values to them
  • Use the core C# data types: int, double, decimal, bool, char, and string
  • Explain what "strongly typed" means and why it helps you
  • Use var, constants, and follow C# naming conventions

Estimated Time: 45 minutes

Project: Build a small program that stores and displays a "profile" of mixed data types.

In This Lesson

What Is a Variable?

A variable is a named container that holds a piece of information while your program runs. You put a value into it, and later you can read it back or change it — all by referring to its name.

📖 Definition

Variable: A named location in the computer's memory that stores a value your program can use and change.

The classic analogy is a labeled box. You write a label on the box (the variable's name), and you put something inside it (the value). When you need what's inside, you just ask for the box by its label.

graph LR A["Label: age"] --> B["Box holds: 30"] C["Label: name"] --> D["Box holds: 'Ada'"] style A fill:#eff6ff,stroke:#3b82f6,stroke-width:2px style C fill:#eff6ff,stroke:#3b82f6,stroke-width:2px

Declaring and Assigning

Before you use a variable in C#, you declare it: you state its type (what kind of value it holds) and its name. Here's the pattern:

// type   name  =  value ;
int age = 30;

Reading that line: "Make an int (whole number) called age, and put 30 in it." Let's name the parts:

  • Declaration — introducing the variable with a type and name: int age;
  • Assignment — putting a value in it using the = sign: age = 30;
  • You can do both at once (as above), which is the most common style.

⚠️ = does not mean "equals"

In C#, a single = means "put the value on the right into the variable on the left." It's an assignment, not a statement of equality. So age = 30; reads as "let age become 30." (Checking whether two things are equal uses ==, which you'll meet in the next lesson.)

Once declared, you can change a variable's value by assigning again — no type needed the second time:

int score = 10;
Console.WriteLine(score);   // 10

score = 25;                 // reassign
Console.WriteLine(score);   // 25

score = score + 5;          // use the old value to make the new one
Console.WriteLine(score);   // 30

Output:

10
25
30

The Core Data Types

The type tells C# what kind of data a variable holds and what you can do with it. Here are the ones you'll use constantly:

Type Holds Example value
int Whole numbers (no decimal point) 42, -7, 0
double Numbers with decimals (general-purpose) 3.14, -0.5
decimal Precise decimals, ideal for money 19.99m
bool A true/false value true, false
char A single character, in single quotes 'A', '?'
string Text (zero or more characters), in double quotes "Hello"

Here they are in action:

int age = 30;
double height = 1.75;          // meters
decimal price = 19.99m;        // note the 'm' suffix for decimal
bool isStudent = true;
char grade = 'A';
string name = "Ada Lovelace";

Console.WriteLine(name);       // Ada Lovelace
Console.WriteLine(age);        // 30
Console.WriteLine(isStudent);  // True

⚠️ Watch the quotes and suffixes

  • Double quotes " " make a string (text); single quotes ' ' make a single char.
  • A decimal literal needs an m suffix: 19.99m. Without it, C# reads 19.99 as a double.
  • bool values are the lowercase keywords true and false.

💡 double vs. decimal — which for numbers?

Use double for general measurements (heights, weights, scientific values). Use decimal for money, where exact cents matter — double can introduce tiny rounding errors that are unacceptable for currency.

Why Types Matter (Type Safety)

C# is a strongly typed (or "type-safe") language. Once a variable has a type, it can only hold values of that type. Try to put the wrong kind of value in, and the program won't even compile:

int age = 30;
age = "thirty";   // ❌ Error! Can't put text into an int

Build error:

Cannot implicitly convert type 'string' to 'int'

This might feel strict, but it's one of C#'s biggest gifts to you as a beginner. The compiler catches a whole category of mistakes before your program ever runs, and the error message tells you exactly what went wrong and where.

💡 Think of it as guardrails: Types are labels on your boxes that also enforce what's allowed inside. A box labeled "whole numbers" simply refuses text — so you can't accidentally mix things up later.

✅ Pro Tip

Read compiler errors carefully instead of fearing them. They almost always name the problem, the type involved, and the line number. Learning to read them is a core programming skill — and C#'s are unusually clear.

The var Keyword

When you assign a value as you declare a variable, C# can often figure out the type for you. The var keyword says "you work out the type from the value on the right":

var age = 30;             // C# infers: int
var name = "Ada";         // C# infers: string
var price = 19.99m;       // C# infers: decimal
var isReady = true;       // C# infers: bool

These are exactly the same as writing the type explicitly — var is a convenience, not a different kind of variable. The variable is still strongly typed; C# just saves you from repeating the type.

⚠️ var still needs a value

Because C# infers the type from the value, you must assign something at the same time. This is an error:

var mystery;   // ❌ Error — no value to infer the type from

And once inferred, the type is fixed. A var that started as an int can't later hold text.

💡 When to use var

As a beginner, prefer the explicit type (int age = 30;) while you're learning — it keeps the type visible and reinforces what's going on. Use var when the type is obvious from the right-hand side. Both are common in real code.

Constants and Naming

Constants

Sometimes a value should never change while the program runs — like the number of days in a week, or a tax rate. Mark it with const, and C# will refuse any attempt to change it:

const int DaysInWeek = 7;
const double Pi = 3.14159;

// DaysInWeek = 8;   // ❌ Error — a const can't be reassigned

Constants make your intent clear and prevent accidental changes to values that should stay fixed.

Naming rules and conventions

C# has a few rules (must-follow) and some conventions (strongly recommended style):

Guideline Good Avoid
Use meaningful names studentAge x, a1
Local variables: camelCase firstName FirstName, first_name
Start with a letter or underscore total 2ndValue (can't start with a digit)
No spaces or most symbols userName user name, user-name
Don't use reserved keywords count int, class
💡 Names are documentation: Good variable names make code read almost like plain English. totalPrice tells the reader far more than tp or x. C# is also case-sensitive, so age and Age are two different names.

Putting It Together

Here's a small program that stores a profile using several types, then prints it. Create a project (dotnet new console -o Profile), paste this into Program.cs, and run it:

// A simple profile using several data types
string name = "Ada Lovelace";
int birthYear = 1815;
double favoriteNumber = 42.5;
bool likesCoding = true;
char initial = 'A';

Console.WriteLine("Name: " + name);
Console.WriteLine("Birth year: " + birthYear);
Console.WriteLine("Favorite number: " + favoriteNumber);
Console.WriteLine("Likes coding: " + likesCoding);
Console.WriteLine("Initial: " + initial);

Output:

Name: Ada Lovelace
Birth year: 1815
Favorite number: 42.5
Likes coding: True
Initial: A

Notice the + between text and a variable. When one side is a string, + joins (concatenates) them into one piece of text, automatically converting the number or bool to its text form. (In the next lesson we'll meet a cleaner way to do this called string interpolation.)

✅ Notice

A bool prints as True/False (capitalized) even though you write true/false in code. That capitalized form is just how C# displays it as text.

Exercise & Quiz

🏋️ Exercise: A Product Receipt

Objective: Practice choosing the right type for each piece of data.

Instructions:

  1. Create a new project called Receipt.
  2. Declare variables for a product: a name (text), a quantity (whole number), a unit price (money), and whether it's in stock (true/false).
  3. Add a const for a store name that never changes.
  4. Print each value on its own line with a descriptive label.

Starter Code:

// TODO: pick the correct type for each variable
const string StoreName = "Ada's Shop";
string productName = "Notebook";
// int quantity = ...;
// decimal unitPrice = ...;
// bool inStock = ...;

Console.WriteLine("Store: " + StoreName);
Console.WriteLine("Product: " + productName);
// print the rest...
💡 Hint

Quantity is a whole number → int. A price is money → decimal (don't forget the m suffix, e.g. 2.50m). "In stock" is yes/no → bool. Join labels and values with +.

✅ Solution
const string StoreName = "Ada's Shop";
string productName = "Notebook";
int quantity = 3;
decimal unitPrice = 2.50m;
bool inStock = true;

Console.WriteLine("Store: " + StoreName);
Console.WriteLine("Product: " + productName);
Console.WriteLine("Quantity: " + quantity);
Console.WriteLine("Unit price: " + unitPrice);
Console.WriteLine("In stock: " + inStock);

Output:

Store: Ada's Shop
Product: Notebook
Quantity: 3
Unit price: 2.50
In stock: True

🎯 Quick Quiz

Question 1: Which type is the best choice for a person's age in whole years?

Question 2: In C#, what does a single = do?

Question 3: Why won't int age = "thirty"; compile?

Summary

🎉 Key Takeaways

  • A variable is a named box that stores a value; you declare it with a type and name, and assign with =.
  • Core types: int (whole numbers), double/decimal (decimals; use decimal for money), bool (true/false), char (one character), string (text).
  • C# is strongly typed: a variable only holds its declared type, and mismatches are caught at compile time.
  • var lets C# infer the type from the assigned value — still strongly typed, just less typing.
  • Use const for values that never change, and follow naming conventions (meaningful names, camelCase locals, case-sensitive).

📚 Additional Resources

🚀 What's Next?

Now that your programs can store data, the next step is to work with it. In Lesson 2.2: Operators and Expressions, you'll do math, compare values, and combine true/false conditions.

🎉 Nicely done!

You've learned how programs remember things. Next, we'll make them calculate.