According to the Microsoft Docs:
There are two common use cases for local functions: public iterator methods and public async methods. Both types of methods generate code that reports errors later than programmers might expect. ... The technique can be employed with async methods to ensure that exceptions arising from argument validation are thrown before the asynchronous work begins:
public Task<string> PerformLongRunningWork(string address, int index, string name)
{
if (string.IsNullOrWhiteSpace(address))
throw new ArgumentException(message: "An address is required", paramName: nameof(address));
if (index < 0)
throw new ArgumentOutOfRangeException(paramName: nameof(index), message: "The index must be non-negative");
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException(message: "You must supply a name", paramName: nameof(name));
return longRunningWorkImplementation();
async Task<string> longRunningWorkImplementation()
{
var interimResult = await FirstWork(address);
var secondResult = await SecondStep(index, name);
return $"The results are {interimResult} and {secondResult}. Enjoy.";
}
}
I don't really understand this example. If we just get rid of the local function and extract its contents to the outer scope and put them right after the validation, won't we achieve the same result? What does the local function actually give in this case?
If it actually doesn't improve anything, can you come up with a better example?
See Question&Answers more detail:os