Domanda

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

È stato utile?

Soluzione

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()

Altri suggerimenti

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

Make the return type of the method Task<List<Photos>> instead of Task. When you call GetPhotos, use

var photos = await GetPhotos

photos will be of type List<Photos>. (The await keyword essentially extracts the List<Photos> object from the Task.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top