New C# 7 features in action: Local Functions in C# 7

C# 7’s Local Functions

1. Overloading not supported.

2. Accessibility modifier (public, private, protected) not allowed.

3. Compiler will issue a warning if not used

4. All variables in the enclosing scope, including local variables can be accessed: (as shown in example below)

invalidData local variable of  IsValidInputDataWithLogging function can be accessed by LogInvalidDataMessages local function.

5. Are in scope for the entire method in which they are present:  (as shown in example below)

Use Cases for C# 7’s Local Functions

A. Parameter validation scenario

In the below example, RequestIsValid local function is used to validate the parameters of InsertNews function.

B. Iterator functions

In case of iterators functions, non-iterator wrapper public function is commonly needed for eagerly checking the arguments at the time of the call. Local function as best suited in this use case.

C. Methods that are called from only one place & only makes sense inside of a single method that uses it

In the below example,  LogInvalidDataMessages and HasValidValues local functions  are available inside IsValidInputDataWithLogging function. In this case, LogInvalidDataMessages and HasValidValues functions are only used by IsValidInputDataWithLogging function.

Full sample code to explain the use of C# 7’s Local Function

Note the use of Local Functions:

  1. Parameter validation scenario (RequestIsValid local function inside InsertNews function)
  2. Iterator functions (ValidBooksForDisplay iterator function)
  3. Methods that are called from only one place & only makes sense inside of a single method that uses it (LogInvalidDataMessages and HasValidValues local functions inside IsValidInputDataWithLogging function)

in the below sample code:

Happy Coding !!!

Kapil Khandelwal

Web Developer, Blogger, Microsoft Certified Professional (MCP), DZone's Most Valuable Blogger (MVB)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *