Lesson 4 / 26

Types, var and Nullability

Declare variables, interpolate strings and handle nullable reference types.

Static types, inferred

C# is statically typed: every variable has a type known at compile time. var lets the compiler infer it, but the type is still fixed. var n = 5; is an int, not a dynamic value.

Data, behaviour, async

Most .NET code models data, transforms collections, and awaits slow I/O.

Three stages: types, collections, async work.
Figure 2.1 — Types, collections and async I/O.

Nullable reference types

With Nullable enabled, string means "never null" and string? means "may be null". The compiler warns before you dereference a possible null.

string name = "Asha";
string? nickname = null;

Console.WriteLine($"Hi {name}");
Console.WriteLine(nickname?.Length ?? 0);

Output:

Hi Asha
0

Do not silence warnings with !

The ! operator tells the compiler "trust me, not null". If you are wrong you still get a NullReferenceException at runtime. Prefer a null check or ?. instead.

Quick check: What does `string?` mean with Nullable enabled?

  • The string is always empty
  • The string may be null
  • The string is read-only
  • The string is a number
Answer

The string may be null — The `?` marks a reference type as allowed to be null, so the compiler makes you handle that case.