'Why we need IEnumerable<string> before get method?

I just started learning web API using ASP.NET. I created a new project from visual studio and trying to understand MVC folder structure and API calls.

Here what I want to know is: why do we need IEnumerable<string> before the get method.

In myValuesController.cs,

        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

According to the Microsoft Documentation, this exposes the enumerator, which supports a simple iteration over a collection of a specified type but think if I have an integer in my database do I need to convert it into string as well?



Solution 1:[1]

In addition, you can return IHttpActionResult with string values:

public IHttpActionResult Get()
{
    var model = new string[] { "value1", "value2" };
    return Ok(model);
}

or with int values:

public IHttpActionResult Get()
{
    var model = new int[] { 1, 2, 3 };
    return Ok(model);
}

IHttpActionResult allows you to return HTTP statuses and more. Here are some advantages of using the IHttpActionResult interface:

  • Simplifies unit testing your controllers.
  • Moves common logic for creating HTTP responses into separate classes.
  • Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.

Solution 2:[2]

If your GET-endpoint should return a collection of numbers instead of a single number, you surely need to return some kind of list, be it IEnumerable or List or whatever.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mr. Tamil