Reputation: 16900
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 :)
Upvotes: 2
Views: 489
Reputation: 754545
Eric Lippert did a nice article on this
I encourage you to read the article but the gist of the article is that the reason the return value appears on the right is that it's the most natural position for it. It is the natural choice for both the English language, mathematics and higher order functions. C# has the return type first for historical reasons.
Upvotes: 2
Reputation: 68667
The full declaration for System.Func
you're talking about is
public delegate TResult Func<T, TResult>(T arg)
So when you do
Func<int, int> sqr = x => x * x;
You're declaring a method using a lambda expression which takes an int x and returns x * x. So right now sqr
is holding a reference to your method. And in the following line
Console.WriteLine(sqr(3));
You actually execute the method and show the output.
Upvotes: 3