Variables and Data Types

Beginner 20 min read Lesson 3 of 13

What are Variables?

A variable is like a labeled box where you can store information. Think of it as a container in your computer's memory that holds data you want to use later.

Name
A label for your data

Type
What kind of data

Value
The actual data stored

Think of it like this: int age = 25; means: "Create a box called age that can hold whole numbers, and put the number 25 in it."

Common Data Types

In C#, each variable must have a data type. The type tells the computer:

  • What kind of data the variable can store
  • How much memory to reserve
  • What operations you can perform on it

Value Types (Store actual data)

Type Description Example Range
int Whole numbers (no decimals) int age = 25; -2 billion to 2 billion
double Decimal numbers double price = 19.99; Very large/small decimals
bool True or False bool isActive = true; true or false
char Single character char grade = 'A'; Any character
decimal High precision decimals decimal salary = 50000.50m; Very precise (best for money)
Tip: Use decimal for money, double for scientific calculations, and int for counting.

Reference Types (Store a reference to data)

Type Description Example
string Text (a sequence of characters) string name = "John Doe";
array A list of items int[] numbers = {1, 2, 3};
DateTime Date and time DateTime today = DateTime.Now;
object Can hold any type object something = 42;
// ===== VALUE TYPE EXAMPLES =====
int age = 25;                    // Whole number
double price = 19.99;            // Decimal number
bool isActive = true;            // True or false
char grade = 'A';                // Single character
decimal salary = 50000.50m;    // High precision (money)

// ===== REFERENCE TYPE EXAMPLES =====
string name = "John Doe";        // Text
int[] numbers = { 1, 2, 3 };    // Array of numbers
DateTime today = DateTime.Now;   // Current date and time
object something = 42;           // Can hold anything

Declaring Variables

To create a variable, you need to tell C#: What type of data it will hold, what name to give it, and optionally what value to put in it.

Explicit Typing (Tell C# the type)

You specify the type directly. This is clear and explicit.

// Explicit typing - you tell C# the type
int count = 10;                    // count is an integer
string message = "Hello";          // message is a string
double pi = 3.14159;              // pi is a double
bool isReady = false;             // isReady is a bool

Implicit Typing (Let C# figure it out)

Use var and let C# figure out the type based on the value you assign. This is shorter and cleaner when the type is obvious.

// Implicit typing - C# figures out the type
var number = 42;        // C# knows this is an int
var text = "Hello";     // C# knows this is a string
var isReady = false;    // C# knows this is a bool
var price = 19.99;     // C# knows this is a double
When to use var? Use var when the type is obvious from the assignment (like var name = "John"). Use explicit typing when the type is not obvious or you want to be extra clear.

Naming Rules

Variable names must follow these rules:

Allowed: letters, numbers, underscore (_)
Allowed: start with letter or underscore
Allowed: meaningful names (like studentName)
NOT Allowed: start with a number (1name)
NOT Allowed: spaces (my name)
NOT Allowed: special characters (@, #, $)
// ===== GOOD NAMES =====
string studentName = "Alice";
int studentAge = 20;
bool isEnrolled = true;
decimal monthlyFee = 150.50m;

// ===== BAD NAMES =====
// int 1stName = 10;    // ERROR: starts with number
// string my name = "John"; // ERROR: has a space
// string @name = "John"; // ERROR: has special character
// int x = 10;           // BAD: not descriptive
Best Practice: Use camelCase for variable names (e.g., studentName, isActive).

Constants

A constant is a variable whose value cannot change once you set it. Use const for values that never change.

// Constants - values that never change
const double Pi = 3.14159;        // Pi never changes
const int MaxValue = 100;          // Maximum allowed
const string AppName = "MyApp";     // Application name

// You CANNOT change a constant
// Pi = 3.14; // ERROR: Cannot assign to a constant
When to use constants? Use constants for values that never change like PI, tax rates, or application names.

Nullable Types

By default, value types (like int, bool) cannot be null. But sometimes you need to represent "no value". That's where nullable types come in.

// Nullable types - can hold null
int? age = null;           // Age is unknown
bool? isMember = null;     // Membership status unknown

// Check if it has a value
if (age.HasValue)
{
    Console.WriteLine($"Age: {age.Value}");
}
else
{
    Console.WriteLine("Age not provided");
}

// Using the null-coalescing operator
int actualAge = age ?? 0;  // If age is null, use 0
Important: Use HasValue to check if a nullable variable has a value before using it.

Type Conversions

Sometimes you need to convert data from one type to another.

// ===== IMPLICIT CONVERSION (Automatic) =====
int num = 10;
double numDouble = num;  // Works automatically

// ===== EXPLICIT CONVERSION (Cast) =====
double pi = 3.14;
int piInt = (int)pi;  // piInt = 3 (loses decimal part)

// ===== USING CONVERT CLASS =====
string numberString = "123";
int number = Convert.ToInt32(numberString);

// ===== PARSING =====
string input = "456";
int parsedNumber = int.Parse(input);

// ===== SAFE PARSING =====
if (int.TryParse(input, out int result))
{
    Console.WriteLine($"Parsed successfully: {result}");
}
else
{
    Console.WriteLine("Invalid number");
}

Practical Examples

🔢 Counting Items
int itemCount = 50;
💵 Money Calculation
decimal total = 99.99m;
✅ On/Off Status
bool isLoggedIn = true;
📝 User Name
string userName = "Alice";
📅 Current Date
DateTime today = DateTime.Now;
📊 Average Score
double average = 87.5;

Quick Reference Table

Data Type Used For Example Size
int Whole numbers int age = 30; 4 bytes
double Decimal numbers double price = 19.99; 8 bytes
decimal High precision decimal salary = 50000m; 16 bytes
bool True/False bool active = true; 1 byte
string Text string name = "John"; Variable
char Single character char grade = 'A'; 2 bytes
DateTime Date and time DateTime now = DateTime.Now; 8 bytes

Exercise: Student Information System

Task: Create a student information system using variables.

Instructions:
  1. Create a console application called "StudentInfo"
  2. Declare variables for a student:
    • First name (string)
    • Last name (string)
    • Age (int)
    • Grade average (double)
    • Is enrolled (bool)
    • Enrollment date (DateTime)
  3. Assign values to each variable
  4. Print all student information to the console
  5. Use string interpolation ($"Hello {name}")
  6. Use at least one constant for something like the school name
  7. Use a nullable type for the student's graduation year
Hint: Your output should look like:
Student Name: John Doe
Age: 20
Grade Average: 87.5
Enrolled: True
Enrollment Date: 1/15/2024
School: C# Mastery Academy
Key Takeaway

Variables are containers for data. Choose the right data type for your data. Use camelCase for variable names. Use var when the type is obvious. Use constants for values that never change.

Test Your Knowledge - Take Quiz