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.Year - dob.Year -
     ((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);

  }
}

Notes

  • The static modifier prevents accidental capture of enclosing variables which could lead to unexpected allocations or bugs
  • All parameters must be explicitly passed to a static local function
  • The compiler will error if a static local function references any instance or local variables from the enclosing scope

More information