I came across a situation where i need some knowledge.
Below is the code:
// A function to match the delegate
public static int DoSomething()
{
Console.WriteLine("i am called");
return 1;
}
// Usage
Action action = () => DoSomething();
Func<int> func = () => DoSomething();
action();
func();
My understanding of Action
used to be that it should match a delegate that accepts no parameter and returns nothing.
And for Func<int>
that it should match a delegate that accepts no parameter and returns an int
.
DoSomething
method returns an integer, hence my question: () => DoSomething()
is a delegate that returns an int
. Func
works as expected, but Action
doesn't. Why? What am i failing to understand here?
The code compiles and runs properly, both output i am called
. What i want to know is that why Action action = () => DoSomething();
is not a compile time error?
What i want to know is that why
Action action = () => DoSomething();
is not a compile time error?
It compiles because you've got a lambda expression that calls the method but ignores the result. You couldn't use a method group conversion, e.g.
// Compile-time failure
// error CS0407: 'int Test.DoSomething()' has the wrong return type
Action action = DoSomething;
(The same method group conversion for Func<Action, int>
is fine.)
But instead, you're doing something more like this:
Action action = DoSomethingAndIgnoreResult;
...
private static void DoSomethingAndIgnoreResult()
{
DoSomething(); // Hey, I'm ignoring the result. That's fine...
}
See more on this question at Stackoverflow