Use local functions in C# to encapsulate logic to a single calling method

💡 – Did you know we can use local functions in C# to scope logic only to their containing methods?

For readability it can be a big help to break up large methods into smaller well-named methods. When we use private methods for this however, they are scoped privately to the class when really they are intended to be called from only one method.

Local functions are available from C# 7 and can make the intent of our code clearer and give it a better way to document itself.

Anyone reading our code can see that the method is not callable except by the containing method. For team projects, they also make it impossible for another developer to mistakenly call the method directly from elsewhere in the class.

The example below shows two local functions, ValidateAccounts and ValidateFunds which are callable only by the TransferFunds public method, thus they do not ‘pollute’ the class private space unnecessarily.

Local functions can be particularly useful when used with recursion ….

What do you think? Many devs will still prefer to use private methods but I really like these. Have you used local functions in C# before?