Defaults & generators in C#
Empty sequences without the exceptions.
var empty = Array.Empty<int>();
// FirstOrDefault hands back a default instead of throwing
Console.WriteLine(empty.FirstOrDefault());
Console.WriteLine(empty.FirstOrDefault(-1));
// DefaultIfEmpty keeps aggregate math safe on empty input
Console.WriteLine(empty.DefaultIfEmpty(0).Average());
// Range and Repeat conjure sequences from nothing
Console.WriteLine(string.Join(",", Enumerable.Range(5, 4)));
Console.WriteLine(string.Join(",", Enumerable.Repeat("ok", 3)));
How it works
FirstOrDefaultreturns a default — or the fallback you pass.DefaultIfEmpty(0)keepsAveragefrom throwing on empty input.RangeandRepeatconjure test sequences from nothing.
Keywords and builtins used here
intstringvar
The run, in numbers
- Lines
- 12
- Characters to type
- 471
- Tokens
- 97
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 61 seconds.
Step 3 of 3 in Materializing & sets, step 15 of 17 in LINQ in depth.