When I run these 2 lines of code I get what I expect:
Func<int, int> sqr = x => x * x;
Console.WriteLine(sqr(3));
But I don’t understand why the return is specified as the 2nd argument? How does it all work? When you define a delegate it has to be:
return-type delegate delName (parameters);
However, with Func delegate, the return type is also specified as the input argument. Can anybody explain me how it all works? And if possible, write a small example using the same concept of specifying the return type as the input parameter. I find it very difficult to understand what is happening under the hood.
Thanks in advance 🙂
The full declaration for
System.Funcyou’re talking about isSo when you do
You’re declaring a method using a lambda expression which takes an int x and returns x * x. So right now
sqris holding a reference to your method. And in the following lineYou actually execute the method and show the output.