Skip to content

Static local functions C# 8.0correctnessperformance

Allow local functions to be declared static so they do not capture the class.

Local functions C# 7.0 provide the ability to ensure a function is not called outside its intended function as well as referencing any variables available to the containing parent function.

C# 8.0 allows local functions to be declared static to indicate they do not reference (and therefore capture) any of the parent functions scope.

Code

C#
public string GetNameAndAge()
{
  return $"{Name} is {CalculateAge(DateOfBirth)} years old.";

  static int CalculateAge(DateTime dob)
  {
    var now = DateTime.Now;
    return now.Years - dob.Years -
     (now.Month < dob.Month || (now.Month == dob.Month && now.Day < dob.Day)) ? 1 : 0;
  }
}
C#
public string GetNameAndAge()
{
  return $"{Name} is {CalculateAge(DateOfBirth)} years old.";

  int CalculateAge(DateTime dob)
  {
    var now = DateTime.Now;
    // Accidentally captures the parent function's scope by referencing DateOfBirth directly
    return now.Year - DateOfBirth.Year -
         (now.Month < dob.Month || (now.Month == dob.Month && now.Day < dob.Day) ? 1 : 0);

  }
}

More information