using System;
class Program {
// *** before: ***
// a value type could not hold "no value", so a missing number was
// encoded by a magic constant or carried a second flag next to it
const int NoAge = -1;
static int FindAgeOld(string name) {
if (name == "Ann") return 31;
return NoAge; // the caller has to know about -1
}
// *** in version 2.0: ***
// int? is Nullable<int>: the same number plus the state "no value"
static int? FindAgeNew(string name) {
if (name == "Ann") return 31;
return null;
}
static void Main() {
int old = FindAgeOld("Bob");
Console.WriteLine(old == NoAge ? "unknown" : old.ToString());
int? age = FindAgeNew("Bob");
Console.WriteLine(age.HasValue ? age.Value.ToString() : "unknown");
int? found = FindAgeNew("Ann");
Console.WriteLine(found.GetValueOrDefault());
Console.WriteLine(found + 1); // 32, arithmetic lifts to int?
// a comparison with an empty value is false on BOTH sides
Console.WriteLine(age > 0); // False
Console.WriteLine(age <= 0); // False as well
}
}