Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to store objects being returned from Async methods?

So 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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

BUT It says: "cannot implicitly convert type ‘system.threading.tasks.task’ 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading