Understanding a delegate’s lambda parameters in a function

Asked

Viewed 104 times

3

I have the function below. I would just like to understand who is X and what values it is reaching in the course of the function. I could not catch the debug. You don’t have to say the exact values literally, but as it is being measured. I am studying and I want to understand all this.

public int qualquerCoisa(int tamanho)
        {
            Func<int, int> calcFib = null;

            calcFib = x => (x - 1 + x - 2);

            return calcFib(tamanho);
        }
  • The code above, I know it’s wrong. I just put it to say what I’m trying to do. The result would be: 0,1,1,2,3,5,8,13,21,34, i.e., a returned list or array.

  • Please do not send code ready. I just need to understand so I can do and reach my conclusions.

  • 1

    She should not have edited the question. She now asks something different from the original request, leaving the answers given in some way meaningless. Instead of editing you should give this question as closed and create a new one.

  • OK, I’ll remove the edit and close and do another.

2 answers

2

The X represents the parameter that is passed to the function calcFib. If you rewrite the function calcFib how a method would look:

public int calcFic(int x)
{
    return x - 1 + x -2;
}

In the case of the code you placed, X will receive the value of tamanho.

  • That is, in the specific case, it does not travel up to the maximum value, starting at a certain value. You would have to pass an array or list, so that it would go through the size value, specifically speaking in the above case.

  • Exactly. If you want the function to be executed for a list you can: or create a cycle for and pass the values one by one to the function. Or change the function to accept a list/array and inside the function run the cycle for.

2

Func<int,int> declares a delegate representing a function that receives a parameter of type int and returns a value of type int.

Taking your example the result of return calcFib(tamanho); will be:

int resultado = tamanho - 1 + tamanho - 2;  

The value that x receives is the one who is passed to the function.

Browser other questions tagged

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