Why we need IEnumerable<string> before get method?

Viewed 632

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?

3 Answers

IEnumerable<string> is a return type of Get() action method. If your api is returning any value then you need to give that type as a return type of a function

If I have an integer in my database do I need to convert it into string as well?

  • No, then you can return given integer and return type of that api endpoint will be int,

like,

    //+ Access Modifier
    //|     + Return Type           
    //|     |    + Function name
    public int Get()
    {
        return 200; //status code for Ok.
    }

Regarding IEnumerable<>:

If you have multiple integers and want to return collection of these integers, then use IEnumerable<int>

From MSDN documentation IEnumerable Interface:

Exposes an enumerator, which supports a simple iteration over a non-generic collection.

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.

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.

Related