Why use local functions?

Asked

Viewed 49 times

1

Recently it was introduced in the C# 7.0 local functions, where you can create unsigned functions or methods within other nested form methods/functions.

int MinhaFormula(int x, int y) {
    int y = x + calculoInterno(x, y);
    return y - x;

    int calculoInterno(int a, int b) {
        return b + a - (3 * b);
    }
}

Why use functions nested to others? I don’t understand the usefulness of using functions where they will be visible only to one function. Why Microsoft did this?

  • Does one or all of them answer the question? https://answall.com/q/181290/101, https://answall.com/q/293979/101, https://answall.com/q/130191/101, https://answall.com/q/142150/101 .

  • @Maniero no. Answers with what is useful to use the local functions, but I still do not know why to use them. From what I have seen in the examples, these functions are general and are not objective to the function where it is declared, seeing then the possibility of nesting these local functions to a larger scope than covering only one function.

1 answer

1


Quoting the documentation:

Local functions make the intent of your code clear. Anyone reading your code will be able to see that the method cannot be called, except by the method that contains it. For team projects, they also make it impossible for another developer to call the method by mistake directly from anywhere else in the class or struct.

That is, local functions are added in order to make it clear what scope is attached, and to prevent distracted developers from calling this function in another part of the class that should not have access. This is useful when a function needs several repeated snippets of code, but must refer exclusively to that scope.

Let’s imagine the following context: there is a method that will have to repeat several times a specific calculation, to not have code replication, I can encapsulate this calculation in a local function, which can only be executed by this method. Quite simply, we can use the following example for this:

public class Exemplo
{
    public static void Main()
    {
        Console.WriteLine(SomaDeSomatarias(100,200,300));
    }

    private static int SomaDeSomatarias(int numero1, int numero2, int numero3)
    {
         var soma1 = Somatoria(numero1);
         var soma2 = Somatoria(numero2);
         var soma3 = Somatoria(numero3);

         return soma1 + soma2 + soma3;
         int Somatoria(int num)
         {
             var soma = 0;
             for(var i = 1; i < num; i++) {
                 soma += i;
             }
             return soma;
         }
    } 
}

Of course, this is just a simple example, but this can be used for various purposes, such as the processing of filenames, whose rule is relative exclusively to a given context.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.