Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we need IEnumerable<string> before get method?

Tags:

c#

asp.net

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?

like image 482
INDRAJITH Avatar asked Jul 20 '26 16:07

INDRAJITH


1 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.

like image 149
Prasad Telkikar Avatar answered Jul 23 '26 05:07

Prasad Telkikar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!