Lesson 4 — Storing Data

Variables

C# variables are strongly typed. var enables compile-time type inference without sacrificing safety. Nullable types handle the absence of a value explicitly.

CSHARP — Explicit declarations
string fullName    = "Thandi Mokoena";
int    age         = 22;
double mark        = 74.5;
bool   isEnrolled  = true;

Console.WriteLine($"{fullName}, aged {age}, mark: {mark}%");

var — Compile-Time Type Inference

var tells the compiler to infer the type from the right-hand side. The variable is still strongly typed — you cannot reassign an incompatible value later. Use var when the type is obvious; use explicit types when the code benefits from clarity.

CSHARP — var and const
var name   = "Sipho";   // string — inferred
var year   = 2025;      // int — inferred
var gpa    = 3.7;       // double — inferred

// var is NOT dynamic — this is a compile error:
// var x = 5; x = "hello"; // cannot assign string to int variable

// const — compile-time constant:
const double VatRate     = 0.15;
const int    MaxLearners = 30;

double price = 500.00;
Console.WriteLine($"Total: R{price * (1 + VatRate):F2}");

Nullable Value Types

Value types (int, double, bool) cannot normally hold null. Append ? to allow null — essential for optional data like a mark that has not been recorded yet.

CSHARP — Nullable types
int?    optionalAge  = null;
double? optionalMark = null;

// Check before accessing:
if (optionalMark.HasValue)
    Console.WriteLine($"Mark: {optionalMark.Value}");
else
    Console.WriteLine("Mark not yet recorded.");

// Null-coalescing — provide a default:
double display = optionalMark ?? 0.0;

// Null-coalescing assignment — assign only if currently null:
optionalMark ??= 50.0;
Console.WriteLine($"After ??=: {optionalMark}");

Practice Task

Your Turn

Declare variables for a learner's name, ID number, age, GPA, enrolment date (DateTime.Now), and laptop ownership. Use var for at least two. Add a nullable int? for their SACE number. Print all using interpolation, using ?? to show 0 if the SACE number is null.

Common Mistakes

  • var without an initialiser — var x; is a compile error; the compiler needs a value to infer from.
  • Treating var as dynamic — it is still strongly typed after inference.
  • C# uses bool, not boolean (Java difference).
  • Accessing .Value on a nullable without checking .HasValue first.

Professional Tip

Use var where the type is obvious from the right-hand side. Use explicit types where clarity matters (complex generics, return values of unfamiliar methods).

Mini Quiz

What type does the compiler assign to 'var x = 42;' in C#?