Embedded local functions in C# 7.0
January 23, 2018 2 Comments
Occasionally it happens that we want to group related code within a function without creating another private function for that. C# 7.0 provides a neat way for that in the form of local functions which are functions within functions.
Consider the following example:
public class LocalFunctionsDemo
{
public void RunDemo()
{
int GetDiff(DateTime first, DateTime second)
{
TimeSpan ts = (second - first).Duration();
return Convert.ToInt32(ts.TotalDays);
}
int dayDiff = GetDiff(DateTime.UtcNow, DateTime.UtcNow.AddHours(10));
Console.WriteLine(dayDiff);
}
}