6

C# 7 introduced local nested functions. They provide even better structure to the code but do they improve readability? Are there any standards, recommendations and best practices? What is easier to read for your eyes and aesthetic feelings?

class Nested
{
    void Foo()
    {
        void Bar()
        {
        }

        void Baz()
        {
        }

        Bar();
        Baz();
    }
}

class Usual
{
    void Bar()
    {
    }

    void Baz()
    {
    }

    void Foo()
    {
        Bar();
        Baz();
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
user2341923
  • 4,537
  • 6
  • 30
  • 44
  • 5
    My eye likes the second. But that could just becold habits dying hard. Haha – pim Dec 01 '17 at 12:03
  • 18
    This feels like almost the definition of an opinion-based question. – Jon Skeet Dec 01 '17 at 12:03
  • 1
    Firstly, this is opinion-based. Secondly, IMHO the nested function syntax should only be used when it's useful (e.g. when checking arguments for a method returning an `IEnumerable`) - and for your example, it's not useful. – Matthew Watson Dec 01 '17 at 12:04
  • 1
    By the way this dose two different things. Your private functions can be used in other functions where local functions can't and that is the point of this sintax – Filip Cordas Dec 01 '17 at 12:05
  • readability: second one, the old way, IMHO. I like shorts method calling other (short) methods, the new sintax will make the outer method much longer. Functionally speaking, the second one gives you the ability to write a function that no one else will be able to call in a different context: Is it worth? maybe. really opinion based. – Gian Paolo Dec 01 '17 at 12:05
  • 3
    Also local function can use closures that private functions can't. This has nothing to do with readability but functionality. It would be like asking what is more readable private or public methods the question makes no sense. – Filip Cordas Dec 01 '17 at 12:09
  • I asked a question related to this, however I'm starting to think that local functions have A LOT to offer! Check this out: https://github.com/dotnet/csharplang/issues/1159#issuecomment-348356873 – Matthew Layton Dec 01 '17 at 13:32

0 Answers0