As you know in C# 7.0 added some new features One of them is Local functions. I looked at some examples and use cases of using local functions and found two reasons to use them:
1) Hide function or method. The reason is: if the function had been not a local, it would have been available for other members to accidentally use directly
2) To use variables of "Parent" function
During debugging in refactoring code I couldn't find references to the local functions in Visual Studio. There are references to private function:
It helps when I am debugging or refactoring code. In local functions I couldn't find them:
So, the first question is why local functions don't show summary comments and references?
Some programmers liked using the local functions, but some of them don't. Here is an example (from What's New in C# 7.0 | .NET Blog):
public IEnumerable<T> Filter<T>(IEnumerable<T> source, Func<T, bool> filter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (filter == null) throw new ArgumentNullException(nameof(filter));
return Iterator();
IEnumerable<T> Iterator()
{
foreach (var element in source)
{
if (filter(element)) { yield return element; }
}
}
}
In this case, the reason for using a local function is :
If Iterator
had been a private method next to Filter
, it would have been available for other members to accidentally use directly (without argument checking). Also, it would have needed to take all the same arguments as Filter
instead of having them just be in scope
The second question is why we should use local functions? In this case, we can just remove the local method, because it used only once. if we are afraid of code size or responsibility of code, we can use region:
public IEnumerable<T> Filter<T>(IEnumerable<T> source, Func<T, bool> filter)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (filter == null) throw new ArgumentNullException(nameof(filter));
#region Iterating
foreach (var element in source)
{
if (filter(element)) { yield return element; }
}
#endregion
}
To insert XML comments for a code element
Place your text cursor above the element you want to document, for example, a method.
Do one of the following:
Type /// in C#, or ''' in Visual Basic
From the Edit menu, choose IntelliSense > Insert Comment
From the right-click or context menu on or just above the code element, choose Snippet > Insert Comment
I tested all of 3 ways to insert comment, but none of it works on local funciton.
IDE: VS2015
However there is not disclaimer mentioned in document about "not supporting local function".