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 allow 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
C#
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);
}
}
C#
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);
}
C#
public int GetYearsApart()
{
var now = DateTime.Now;
var calculateAge = (DateTime dob) =>
now.Year - dob.Year -
(now.Month < dob.Month || (now.Month == dob.Month && now.Day < dob.Day) ? 1 : 0);
var age1 = calculateAge(first.DateOfBirth, now);
var age2 = calculateAge(second.DateOfBirth, now);
return Math.Abs(age1 - age2);
}
Notes
- Static local functions C# 8.0 extends this functionality to allow them to be scoped
static
where they will not automatically capture the parent functions scope.