To emphasize that this function is called in one place?
Not necessary. It can be executed many times in the method in which it is nested. Just now, such "locally executed" functions can not be moved to the class. As a result, the class will be cleaner and more readable.
By the way, the nested function has access to the local variables of the method:
var number = 23; void DoAction() { Console.WriteLine(number); // 23 } DoAction();
Also found the benefit of using nested functions in event subscriptions. Let's give an example of how it looked before:
EventHandler createdEventHandler = null; createdEventHandler += (sender, e) => { something.Created -= createdEventHandler; ... }; something.Created += createdEventHandler;
And now with the help of nested functions:
void OnCreated(object sender, EventArgs e) { something.Created -= OnCreated; ... } something.Created += OnCreated;
What looks more readable?
Found another beautiful example posted by VladD :
void SortBy<T>(List<T> list, Func<List, double> expr, bool ascending) { int comparerAscending(T t1, T t2) { return expr(t1).Compare(expr(t2)); } int comparerDescending(T t1, T t2) { return expr(t2).Compare(expr(t1)); } list.Sort(ascending ? comparerAscending : comparerDescending); }
void w<T>(T t)=>Console.Write(t);and if console output is used at least in several places, win a couple of characters:w("Hello");))) - Andrey NOP