user1400915 user1400915 - 20 days ago 9
C# Question

Return Type of an async method

I have an async method in C# as follows:

public async Task<string> GetData(int id)
{
Task<string> inp = CommonMethod(id);
return inp;
}

public async Task<string> CommonMethod(int id)
{
string output ;
output = await service.GetSomeDummyData(id);
return output;
}


I am getting an error message as "Since this is an async method,the return expression must be of type string rather than 'Task'

SO, I converted the return type as :

public async Task<string> GetData(int id)
{
Task<string> inp = CommonMethod(id);
return inp.ToString();
}


The code is getting complied successfully .

I am new to asynchronous programming, is the above conversion method is a best practice of returning string? Because from the CommonMethod,
I am collecting the return type in
Task<string>
, and in the next statement I am using
inp.Tostring()
. Little bit of Dilemma in using the correct return types.

Answer

You should rather do it this way:

public async Task<string> GetData(int id)
{
    string inp = await CommonMethod(id);
    return inp;
}

The same way you do it in your second call. The returned value will get wrapped up in a Task automatically.

Because you had Task as your return type, and you had packed this in Task manually in your code, it was throwing an error there.