UFO
UFO

Reputation: 410

Async Await with custom type C#

I have a model:

public class News
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public ObservableCollection<Comment> Comments { get; set; }
}

public class Comment
{
    public int CommentId {get;set;}
    public string CommentTitle{get;set;}
    public string CommentBody{get;set;}
}


public class APIData()
{

    public async Task<News> myNews()
    {
    var result = new News()
    /// GET xmlDATA

    var objComments = new ObservableCollection<Comment>();
    foreach(x in xmlData)
    {
        var objComment = new Comment();
    ////////////
        objComments.Add(objComment);
    }
    result.Comments = objComments;
    return result;
}

when I try to access it using api.myNews().Comments; I get error said ;

System.Threading.Tasks.Task does not contain a definition for Comments and no extension method accept first argument of type System.Threading.Tasks.Task could be found.

Please let me know. about this issue.

Upvotes: 0

Views: 770

Answers (1)

Dustin Kingen
Dustin Kingen

Reputation: 21275

The method will return at Task which does not contain a property named Comments.

You need to await the Task:

var news = await api.myNews();
var comments = news.Comments;

If the method context is not async then use the Result.

var newsTask = api.myNews();
var comments = news.Result.Comments;

Upvotes: 3

Related Questions