How does the compiler type in the delegate example?

In the following delegate example, how does the compiler infer what type of variable alpha is?

delegate double Doubler(double x);

public class Test
{
    Doubler dbl = (alpha) => //How does it determine what type is alpha?
    {
        return alpha * 2
    };

    Console.WriteLine(dbl(10)); //Is it when the method is called?  int here;

    Console.WriteLine(dbl(5.5)); //double here???
}

I found this expression on a website, I think based on the answers, is this wrong?

"In our example, we specified the type of the argument. If you want, you can let the compiler find out the type of the argument. In this case, pass only the name of the argument, not its type. Example:"

+3
source share
3 answers

You declare it in your delegate.

delegate double Doubler(double x);

x is your alpha.

You can easily replace your code:

Doubler dbl = delegate (double x)
{
   return x*2;
};

You can also simplify the lambda expression:

Doubler dbl = alpha => alpha*2;
+6
source

You indicated that the input type doubles when you define the Doubler delegate. For both examples, the input type is double.

+1
source

Source: https://habr.com/ru/post/1718849/


All Articles