C# Programming · Lesson 2
Living with Variability — Declaring Value-Type Variables
Choose, initialize, convert, and reason about C# variables, value types, precision, dates, and constants.
Lesson purpose
Lesson 2 introduces variables as typed storage locations. Students learn to declare and initialize values, choose numeric and text types deliberately, represent dates and logical states, distinguish value-type copying from reference behavior, use constants and inference, and make conversions visible when information might be lost.
Learning objectives
- Declare identifiers with valid types and initialize them before use.
- Select an integer, floating-point, decimal, Boolean, character, string, or date type based on the data’s meaning.
- Explain integer division and floating-point precision limits.
- Use DateTime, constants, casts, and var intentionally.
- Recognize invalid assignments caused by mismatched types.
1. Variables and initialization
A variable is a named storage location. Its declaration tells C# what kind of data may be stored there, and its initializer gives it a starting value.
int seats;
seats = 24;
double fee = 15.50;
bool isOpen = true;
DateTime today = DateTime.Today;
Students must declare a variable before using it and assign a value before reading it. Identifiers should communicate the domain meaning. C# identifiers are case-sensitive, cannot begin with a digit, and cannot be reserved keywords.
2. Integer types and integer division
int is the normal whole-number choice for counts and indexes. long provides a larger range. short and byte use smaller ranges and fit cases where a format or domain rule requires them. Every integer type has a finite range.
Integer division discards the fractional remainder:
int fahr = 41;
int celsius = (fahr - 32) * (5 / 9); // 5 / 9 is 0
For a fractional result, make the operands fractional before division:
double celsius = (fahr - 32.0) * (5.0 / 9.0);
Modulo returns the remainder and is useful for even/odd tests:
int remainder = 25 % 3; // 1
bool isEven = 24 % 2 == 0;
3. Floating-point and decimal values
float and double store approximate binary floating-point values. double is common for measurements and scientific calculations. A float literal needs the f suffix.
float smallerApproximation = 1.0f;
double actual = 0.1 + 0.2;
Console.WriteLine(actual == 0.3); // Not a reliable equality test
Many decimal fractions cannot be represented exactly in binary. Do not use exact equality for calculated floating-point values when a tolerance is more appropriate.
decimal is designed for base-10-oriented business and financial calculations. Use the m suffix for a decimal literal:
decimal price = 19.95m;
int quantity = 3;
decimal subtotal = price * quantity;
Console.WriteLine($"{subtotal:C}");
The suffix belongs to the literal. A decimal variable should receive a decimal expression rather than an accidental double.
4. Boolean, character, and string values
A bool contains true or false. Comparisons such as enrolled < capacity produce Boolean results.
A char stores one UTF-16 code unit and uses single quotes. A string stores zero or more characters and uses double quotes:
char grade = 'A';
string course = "IST 2373";
string line = "First line\nSecond line";
string path = @"C:\documents\files\myFile.txt";
The backslash introduces escape sequences such as newline and tab. A verbatim string literal begins with @ and treats backslashes as ordinary characters, which is useful for paths. String.Empty represents an empty string. Use char for one character and string for a sequence.
5. Value types, reference behavior, and DateTime
Numeric types, bool, char, and DateTime are value types. Assigning one value-type variable to another copies the value. string is a reference type with special language support and immutable behavior, which is why Lesson 3 treats it separately.
DateTime models dates and times:
int year = 2028;
bool leap = DateTime.IsLeapYear(year);
DateTime now = DateTime.Now;
DateTime tomorrow = now.AddDays(1);
DayOfWeek weekday = now.DayOfWeek;
DateTime dateOnly = DateTime.Today;
IsLeapYear applies the calendar rule. Today has a midnight time component, while Now includes local time. TimeSpan represents a duration that can be added to or subtracted from a date.
6. Constants and inferred local types
A const value must be assigned when declared and cannot be reassigned:
const int Capacity = 24;
const string CourseCode = "IST 2373";
var asks the compiler to infer the compile-time type from the initializer:
var count = 5; // int
var title = "C#"; // string
var measurement = 1.0; // double
var does not remove strong typing. Use it when the inferred type is obvious. Use an explicit type when the declaration itself communicates an important design choice.
7. Conversions and casts
A widening conversion can preserve all source values. A narrowing conversion can discard information and should be explicit:
int count = 10;
double precise = count;
double average = 92.8;
int whole = (int)average;
Console.WriteLine(whole); // 92
A cast changes interpretation for that expression; it does not round automatically. C# does not provide a numeric conversion path to or from bool.
Classroom application
Create a typed enrollment record with a constant capacity, course string, integer enrollment count, decimal fee, Boolean availability result, and DateTime start date. Have students predict each type and then deliberately create one mismatch to see how the compiler exposes it.
Common misconceptions
- Declaration alone does not provide a useful value.
- 5 / 9 is integer division when both operands are integers.
- double is approximate; decimal is the better default for money.
- char uses single quotes and string uses double quotes.
- var is compile-time inference, not a dynamically changing type.
- A cast can discard data and is not a rounding function.
- DateTime.Today and DateTime.Now answer different questions.
Lesson summary
Types encode meaning, range, precision, and available operations. Students can now choose suitable types, initialize values, use constants and inference, and recognize when conversion requires explicit evidence. The next lesson applies typed values to strings and text processing.
Course Notes