Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return types within a Task running an async anonymous function?

Tags:

I have a function that returns a Task<String>, to construct this Task I have to use an anonymous async function because I must await multiple calls within the Task. I have found that I can return "" though if I try to return null an error arises (Visual Studio message)

Anonymous function converted to void returning delegate cannot return a value

Async lambda expression converted to a 'Task' returning delegate cannot return a value. Did you intend to return 'Task'?

A function showing the same issue

public virtual Task<String> FooBar()
{
    return Task<String>.Run(async () =>
    {
        await Task.Delay(1500);
        return ""; // OK
        //return null; // Error 
    });
}

What is happening here?

Would it be more appropriate to return await Task.FromResult<String>(null); if I would like to return a null value?

like image 853
KDecker Avatar asked Aug 08 '16 18:08

KDecker


1 Answers

The compiler does not know that null is a string's null and therefor can't automatically choose the correct type Func<Task<string>>. Do the following instead to tell the compiler that the null is for a string.

return (string)null;

Also, as brought up in the comments, Task.Run<TResult>(Func<Task<TResult>> function) is a static method so when you do Task<String>.Run(... you are still calling the same static method Task.Run with no extra information. What you need to do instead is call it and pass the type in to the Run portion forcing the return type to be string instead of making the compiler try and figure out what the return type should be.

public virtual Task<String> FooBar()
{
    return Task.Run<String>(async () =>
    {
        await Task.Delay(1500);
        return null; // Does not error 
    });
}
like image 69
Scott Chamberlain Avatar answered Sep 22 '22 16:09

Scott Chamberlain