a blog for those who code

Wednesday, 15 February 2017

Lets talk about Local Functions in C# 7

In this post we will be discussing about Local Functions which was introduced in C# 7. C# 7 Local Functions gives you the ability to declare methods and types in block scope. C# 7 allows you to define local methods and they can be called within a method itself. Just think Local Functions as a normal functions but the scope of the local functions is to the block were they have been declared.

In the following code you can see that we have created a Local Function inside the method. Now when we am trying to access it outside that function it throws an error that 'myLocalFunction' does not exist in the current context.

Is Local Functions New to C# Developers ?

Actually not, local functions are not new to developers. You can actually write kind of local functions using Func and Action or simply using lamda's but they lack the features provided by Local functions and they are :

1. Local functions can be a Generic Function whereas Func and Action cannot be Generics.

public void outsideMethod()
   void insideMethod<T>(T value)
   insideMethod<string>("Coding Defined");
2. Local functions support ref and out parameters which has the same functionality as the function whereas in Func and Action you cannot use ref and out parameters.

public void outsideMethod()
  void insideMethod(int a, out int b)
    b = ++a;
   int c = 0;
   insideMethod(0, out c);

3. Local functions can be implemented as an iterator whereas Func and Action cannot be used as an iterator.
4. Local functions looks better and whereas Func and Action could be confusing to read sometimes.

Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us


Email *

Message *


Best Hosting Plans

CC License