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 that return an object from an async task. I would like to do this in the constructor, so I cannot make it the parent async method.

The ReadJsonAsync method returns a Session object. I will show you the corresponding code:

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

Thanks in advance!

+3
c # lambda asynchronous async-await
source share
1 answer

If you want an anonymous method, you will have to declare the one that returns Task<Session> , since it is marked with the async modifier, so it should return void (only for async event handlers), Task or Task<T> :

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

If everything you do is launched by ReadJsonAsync , you can also save yourself the generation of state apparatus as follows:

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

Then you can await on it with a higher order:

 Func<Task<Session>> anonFunction = fileService.ReadJsonAsync; await anonFunction(); 
+5
source share