How to get result from `new Func<T>() { ... }?`

.net, c#

Solution

This line

return additionImplementor();

Calls the function and returns its result which is then passed to `Console.WriteLine()`.

While this line

Console.WriteLine("{0}", new Func<int>(
    () =>
    {
        return 100 + 100;
    }
));

merely passes the function to `Console.WriteLine()` without calling it. Add `()` to execute the function before printing it out...

Console.WriteLine("{0}", new Func<int>(
    () =>
    {
        return 100 + 100;
    }
)());

Fiddle

Problem

Why do these print different things? Let's say I have such class: ``` public class ExampleOfFunc { public int Addition(Func<int> additionImplementor) { if (additionImplementor != null) return additionImplementor(); return default(int); } } ``` And in the `Main` method: This prints `200`: ``` ExampleOfFunc exampleOfFunc = new ExampleOfFunc(); Console.WriteLine("{0}", exampleOfFunc.Addition( () => { return 100 + 100; })); // Prints 200 ``` But this prints `Prints System.Func'1[System.Int32]`: ``` Console.WriteLine("{0}", new Func<int>( () => { return 100 + 100; })); // Prints System.Func`1[System.Int32] ```

Original source