Static local functions
Local functions have been introduced to make the code more readable by constraining the visibility of a certain piece of code to a single method:
void PrintName(Person person) { var p = person ?? throw new ArgumentNullException(nameof(person)); Console.WriteLine(Obfuscated()); string Obfuscated() { if (p.Age < 18) return $"{p.FirstName[0]}. {p.LastName[0]}."; return $"{p.FirstName} {p.LastName}"; } }
In this example, the Obfuscated
method can only be used by PrintName
and has the advantage of being able to ignore any parameter check, because the context where the p
captured parameter is used does not allow its value to be null. This can deliver performance advantages in complex scenarios, but its ability to capture the...