C# 7.0 Potential Features – Local Functions

Thoughts on C# 7.0 Local Functions.

CodeYourWay-Local Functions
Potential Features - Local Functions


Frankly, when I first tried this, I thought that it's just a nice and compact way of defining local helpers. In fact, it's much more interesting and useful feature. Today I'm going to explore and explain it in more details.

Let's  start with a brief overview of the current situation.

Before Local Functions


Private methods


The first option that existed in C# 1 is having a private method.


That’s a clean and simple solution. It has few issues, though.

PrintMe might have no sense outside of ThatTime method, but it’s accessible for every other method inside the class. It will be taken into account by IntelliSense.


Func and Action

We can try to hide our helper inside the scope of ThatTime method by converting it to Func<int, string>:


Any disadvantages ?? Yep, a lot.

The call is unnecessary expensive: it will produce more allocations.

There is no elegant way to define recursive lambda , All we have to do is go ahead and use an ugly trick :


And lastly, lambdas are very limited . You cannot use out,ref,params, and optional parameters . They cannot be made Generic.

Local Functions

Local functions can be defined in the body of any method, constructor or property’s getter, and setter.

Since it will be transformed by compiler to regular private static method and hence there would be no overhead of calling it and it can have all the properties which regular method can have :
  1. It can be Asynchronous.
  2. It can be Generic.
  3. It can be Dynamic.
Local functions cannot be Static . And all local functions can capture variables from enclosing block :



Advantage of using Local Functions:

  • Like lambdas, local functions can capture local variables and parameters of their containing method.
  • Local functions support recursion like any normal methods
  • They don’t require you to allocate a delegate to hold them. This reduces memory pressure and also allows the function to be inlined by the compiler.
  • They don’t require you to allocate an object when creating a closure because it has access to the local variables. Also, this improves performance by reducing GC pressure.

Comments

Popular posts from this blog

The Top 15 Google Products for People Who Build Websites

Google Translator using Windows forms

5 Useful Tricks for Ubuntu Power Users