I have a following async code in C#:
public async Task GetPhotos(List<int> photoIds)
{
List<Photos> photos = new List<Photos>();
if (photoIds != null)
{
foreach (int photoId in photoIds)
{
Photo photo = await ImageRepository.GetAsync(photoId);
if (photo != null)
photos.Add(photo);
}
}
return photos;
}
On the return statement i am getting the following error message:
Since GetPhotos(List photoIds) is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task'?
How to solve this error ??
Change your return type like this Task<List<photos>>
public async Task<List<photos>> GetList()
{
List<Photos> photos = new List<Photos>();
if (photoIds != null)
{
foreach (int photoId in photoIds)
{
Photo photo = await ImageRepository.GetAsync(photoId);
if (photo != null)
photos.Add(photo);
}
}
return photos;
}
To call
var list = await GetList()
An async method returns a Task<T1,T2,T3...>
that shows whether it it complete and allows the caller to use .Result
or async
to retrieve the return value.
If there is no return value, an async method returns a Task
. That it, it returns nothing when it completes.
Your method is defined as returning a Task
, which means it returns nothing on completion, yet at the end of your method you return a List<Photo>
. Therefore, the correct return type would be a Task<List<Photo>>
.
You may wish to read this post.
Also, you have a typo in your sample code: List<Photos>
-> List<Photo>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With