Posts Tagged ‘Local Functions’

Local Functions in C#7.0

Posted: July 30, 2017 in .NET, C#
Tags: ,

The nested functions (methods) or local functions are functions defined inside another function , referred to as the enclosing function. The nested functions are available only within the scope of the enclosing functions. This is nothing new. The nested functions has been there in languages like ALGOL , PASCAL , Lisp , JavaScript for quite sometime and even in modern programming languages like Scala.

Can we do similar stuff in C#?

image

Suppose in the snippet above we want to extract out the computation logic in a separate function. A quick way will be to extract it out to separate private function. But that will be bit confusing, because the scope of the private method will not be restricted to the method Calculate and it will be a class level method. So someone reading the code later, will have difficulty to understand, that my intent was to have this private method only to be used by the Calculate method.

One way of doing this will be to define an anonymous method within the Calculate method. But here I have to define a delegate (type definition) and create a delegate object (first class object in itself) to cater to my simple need of having just a helper function.

image

C#7.0 helps us to achieve this with the feature of local functions , another syntactic sugar coat and added compile time checks. The code below shows how we can define nested local function within another method in C#7.0.

image

This local function gets compiled into a compiler generated private method as shown below, without adding any added overhead.

image

image