C# nullable values, patterns, and switch expressions
A value type such as int cannot normally be null. int? is a nullable int that either holds a value or is null. HasValue tests which, and the null-coalescing operator ?? supplies a default. The null-conditional operator ?. stops and gives null if the object is null, so text?.Length is null for a null string instead of throwing.
C#
using System;
using System.Globalization;
class Program {
static (int Min, int Max) MinMax(int[] values) {
int min = values[0], max = values[0];
foreach (int v in values) {
if (v < min) min = v;
if (v > max) max = v;
}
return (min, max);
}
static void Main() {
int? maybe = null;
Console.WriteLine(maybe.HasValue + " " + (maybe ?? -1));
string text = null;
Console.WriteLine(text?.Length ?? 0);
object[] things = { 42, 7, "hello", 3.5, null, new[] { 1, 2, 3 } };
foreach (object thing in things) {
string description = thing switch {
int n when n > 40 => "big int " + n,
int n => "int " + n,
string s => "string of length " + s.Length,
double x => "double " + x.ToString(CultureInfo.InvariantCulture),
null => "null",
int[] array => "array with " + array.Length + " items",
_ => "something else",
};
Console.WriteLine(description);
}
var (min, max) = MinMax(new[] { 4, 9, 2, 7 });
Console.WriteLine(min + " " + max);
}
}