In C# 7 there the new feature called Local functions in C#. Basically Local functions allow one to write a function within the body of another method or function. It comes in handly in the case lets say you are creating a helper function that are mostly just used in one class or where the declaration makes the code clear of the intention. Local functions also come in handly to write recursive functions rather than using a Lambda for it.

Here are some places where you can use local functions.

  • Methods, especially iterator methods and async methods
  • Constructors
  • Property accessors
  • Event accessors
  • Anonymous methods
  • Lambda expressions
  • Finalizers
  • Other local functions

Below is an example where I Anonymize a string of emails, you can see that I am actually calling the local function below the return statement. Therefore where you can declare a local function below a return statement and also the Pattern variable is available inside the local function, since it is within its scope.

If you wish to read more on local functions take a look at the Microsoft documentation of local functions.