typestar

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

  1. FirstOrDefault returns a default — or the fallback you pass.
  2. DefaultIfEmpty(0) keeps Average from throwing on empty input.
  3. Range and Repeat conjure test sequences from nothing.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Materializing & sets, step 15 of 17 in LINQ in depth.

← Previous Next →