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); } }
Note how GetDiff lies within the boundaries of the RunDemo method. It can only be called from within the declaring function and not from anywhere else, not even from within the containing class. In this sense GetDiff is sort of a super-private function with a very limited scope.
Curiously we can call local functions BEFORE they are declared. The following code is still valid:
public void RunDemo() { int dayDiff = GetDiff(DateTime.UtcNow, DateTime.UtcNow.AddHours(10)); int GetDiff(DateTime first, DateTime second) { TimeSpan ts = (second - first).Duration(); return Convert.ToInt32(ts.TotalDays); } Console.WriteLine(dayDiff); }
View all various C# language feature related posts here.
Can you give an example when somebody should use this kind of function ? When is justified to use embedded local functions ?
I admit that it’s a bit difficult to give an example where this is the “absolute” solution. I can think of the following scenario: if someone looks at a class and reads the signatures of the various methods, both public and private, they can discover the interface and inner workings of the class. Occasionally though you may not want to reveal even that much and rather group a small section of reusable bit of code within a containing class. Also, local functions cannot even be directly executed through reflection.
//Andras