masm64 masm64 - 5 months ago 20
C# Question

Cannot convert lambda expression to type "..." because it is not a delegate type

Good day!
I am trying to write an anonymous method using lambda expressions which would return an object from an async task. I would like to do this in the constructor, so that is the reason I can't make its parent method async.

The ReadJsonAsync method returns a

I will show you the relevant code:

Session session;
fileService = new FileService();
session = async () => { return await fileService.ReadJsonAsync() };

Thanks in advance!


If you want an Anonymous Method, you'll have to declare one which returns a Task<Session> as it is marked with the async modifier, hence must return a void (only for async event handlers), Task or Task<T> :

Func<Task<Session>> anonFunction = async () => await fileService.ReadJsonAsync();

If all you do is run ReadJsonAsync, you may also save yourself the state machine generation like so:

Func<Task<Session>> anonFunction = fileService.ReadJsonAsync;

Then you can await on it at a higher order function:

Func<Task<Session>> anonFunction = fileService.ReadJsonAsync;
await anonFunction();