Nullable reference types (awareness) & annotations (C# 6 patterns)
C# 6 does not have nullable reference types (string?). Learn safe null handling: input guards, clear docs, helper Require.NotNull, and contrast with Nullable for value types.
NRT awareness & fallback
Idea: Nullable reference types (e.g., string?) add compiler checks in newer C#.
- C# 6 does not support string?
- Use guards, clear docs, and simple helpers
- Return non-null by default
Guard against nulls
Add ArgumentNullException guards for reference-type parameters; then treat values as non-null.
using System;
public static class Greeter
{
// Contract: name must not be null (C# 6 has no string? to enforce)
public static string Hello(string name)
{
if (name == null) throw new ArgumentNullException("name"); // guard
return "Hello " + name.ToUpper(); // safe after guard
}
}
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine(Greeter.Hello("Ada"));
try
{
Console.WriteLine(Greeter.Hello(null)); // will throw (by design)
}
catch (Exception ex)
{
Console.WriteLine("Caught: " + ex.GetType().Name);
}
}
}
All lessons in this course
- Generic methods/types; constraints
- Variance (in/out) with interfaces & delegates
- Nullable reference types (awareness) & annotations (C# 6 patterns)