The one and only features of C# 7 that may convince you to upgrade

Emran Hussain,
Mar 12, 2017

When C# 6 came out to the market, I was thinking, why should I bother. What is so nice about C#6 so that I need to upgrade my VS 2013 to VS 2015. I found one, and that was that was compelling enough for me to do the switch. It was nameof(..) operator. Yes, I was highly excited to replace all of my magic strings with nameof(..). All places where I had to use hard-coded property names (WPF ViewModels, dependency properties...etc) was looking nice and strongly typed with nameof(..).

This time, with c#7, I was looking for at least one feature that can convince myself to do the upgrade again. I found that one feature. It is the 'Local Function'.

Local functions

Here is an example of a local function.

private static void Main(string[] args)
{
    int Square(int number)
    {
        return number * number;
    }
 
    Console.WriteLine(Square(100));
}

Well, initially I was thinking, what is the extra benefit in a local function? I can achieve the same goal by using Func<T,T> delegates. Can't I ? Moreover, I was thinking, what an ugly way of writing code. A method should not be complicated; a method should do only one thing. An obese method with many local functions simply stinks. Whenever we see a method is doing lots of things, we should think about encapsulating the logic to a separate class. Why it is beneficial over a Func<T,T> delegate! Then I found the following article where it is explained nicely.

https://github.com/dotnet/roslyn/issues/3911

The bottom line is, the local function is more efficient (performance wise) than a local lambda delegate. When I heard the word ‘performance,' I was sold.

Here is the answer from that page: You want a helper function. You are only using it from within a single function, and it likely uses variables and type parameters that are in scope in that containing function. On the other hand, unlike a lambda, you don't need it as a first class object, so you don't care to give it a delegate type and allocate an actual delegate object. Also, you may want it to be recursive or generic, or to implement it as an iterator.

The answer given by a stack overflow member named ‘svick’ was splendid:
http://stackoverflow.com/a/40949214/647459

Last Modified at Mar 11, 2018
© All content, photographs, graphs and images in this article are copyright protected by SpiceLogic Inc. and may not, without prior written authorization, in whole or in part, be copied, altered, reproduced or published without exclusive permission of its owner. Unauthorized use is prohibited.

Please feel free to share your comment.