Skip to content

Local function statements C# 7.0correctness

Allow functions to be declared inside other functions.

Sometimes functions contain repetitive code that lends itself to being broken up into smaller functions however you were limited to either putting them into a private method that no other function should call or creating a lambda to re-use through the function.

C# 7.0 allows functions to contain other functions to aid in readability and re-use without external methods having access to them. They additionally have access to all the variables in scope of the parent function.

Code ​

csharp
public int GetYearsApart()
{
    var now = DateTime.Now;
    var age1 = CalculateAge(first.DateOfBirth);
    var age2 = CalculateAge(second.DateOfBirth);
    return Math.Abs(age1 - age2);

    int CalculateAge(DateTime dob)
    {
        return now.Year - dob.Year -
            (now.Month < dob.Month || (now.Month == dob.Month && now.Day < dob.Day) ? 1 : 0);
    }
}
csharp
public int GetYearsApart()
{
    var now = DateTime.Now;
    var age1 = CalculateAge(first.DateOfBirth, now);
    var age2 = CalculateAge(second.DateOfBirth, now);
    return Math.Abs(age1 - age2);
}

private int CalculateAge(DateTime dob, DateTime now)
{
    return now.Year - dob.Year -
        (now.Month < dob.Month || (now.Month == dob.Month && now.Day < dob.Day) ? 1 : 0);
}
csharp
public int GetYearsApart()
{
    var now = DateTime.Now;
    Func<DateTime, int> calculateAge = dob =>
        now.Year - dob.Year -
        (now.Month < dob.Month || (now.Month == dob.Month && now.Day < dob.Day) ? 1 : 0);

    var age1 = calculateAge(first.DateOfBirth);
    var age2 = calculateAge(second.DateOfBirth);
    return Math.Abs(age1 - age2);
}

Notes ​

  • Unlike a lambda, a local function can be called before it is declared, can be recursive or generic, can be an iterator (yield return) and avoids allocating a delegate
  • Static local functions C# 8.0 extends this functionality to allow them to be scoped static where they will not automatically capture the parent function's scope
  • Attributes on local functions C# 9.0 allows attributes on local functions and their parameters

More information ​

Powered by Intracia