Search code examples
c#.netasync-awaittask

How to store objects being returned from Async methods?


I have two classes:

    public class Employee
    {
        public string status { get; set; }
        public EmployeeData[] data { get; set; }
        public string message { get; set; }
    }

    public class EmployeeData
    {
        public int id { get; set; }
        public string employee_name { get; set; }
        public int employee_salary { get; set; }
        public int employee_age { get; set; }
        public string profile_image { get; set; }
    }

And I am trying to call to a public API:

// using Newtonsoft.Json;
// using RestSharp;
public static async Task<Employee> getEmployeeData()
    {
        var client = new RestClient("http://dummy.restapiexample.com/api/v1/"); // Base url
        var request = new RestRequest("employees");
        var response = client.Execute(request);

        Employee result = null;
        string rawResponse = "";
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            rawResponse = response.Content;
            result = JsonConvert.DeserializeObject<Fact>(rawResponse); // JSON to C# Object
        }
        return result ;
    }

Then I am trying to store whatever is returned by getEmployeeData() in a variable called employee inside main:

static void Main(string[] args)
    {
        Employee employee = GetCatFact();
    }

BUT It says:

"cannot implicitly convert type 'system.threading.tasks.task<Employee>' to 'Employee'"

So how do I make it so that I can store getEmployeeData() inside the variable employee without changing getEmployeeData()?


Solution

  • Mark your Main method as async one (available since C# 7.1) and call await on the GetCatFact (or getEmployeeData your question is a bit inconsistent):

    static async Task Main(string[] args)
    {
         Employee employee = await GetCatFact(); // or getEmployeeData
    }
    

    Related:

    1. asynchronous programming with async and await
    2. async modifier
    3. await operator