Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: return keyword must not be followed by an object expression in c# async code

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 ??

like image 354
user1740381 Avatar asked Apr 18 '14 04:04

user1740381


2 Answers

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()
like image 142
Sajeetharan Avatar answered Sep 24 '22 06:09

Sajeetharan


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>.

like image 40
K893824 Avatar answered Sep 21 '22 06:09

K893824