-3

I am new to programming. I am having problem understanding the below code.

  1. What is the specific reason we are using IEnumerable here?
  2. return new List {} - is this an anonymous method?
  3. Why can't we use list as a return type rather than IEnumerable?

Sorry if this is a stupid question, but I would really appreciate if someone breaks down the below code.

    private IEnumerable<Customer> GetCustomers()
    {
        return new List<Customer>
        {
            new Customer { Id = 1, Name = "John Smith" },
            new Customer { Id = 2, Name = "Mary Williams" }
        };
user3397379
  • 111
  • 1
  • 2
  • 6
  • If you right click on List and Go To Definition you will see that List implements IEnumerable; in other words, List can be morphed to an IEnumerable. You can return List as the return type too. – JWP Jun 07 '16 at 10:17
  • 1
    Possible duplicate of [IEnumerable vs List - What to Use? How do they work?](http://stackoverflow.com/questions/3628425/ienumerable-vs-list-what-to-use-how-do-they-work) – Pawan Nogariya Jun 07 '16 at 10:19
  • 1
    Question 1 and 3 (and please post only one question per question) is based on opinions. Question 2 is collection initializer. – Lasse V. Karlsen Jun 07 '16 at 10:20

2 Answers2

2
  1. What is the specific reason we are using IEnumerable here?

Don't know. Ask the one who wrote it. One reason to use interfaces is to hide implementation details. The consumer doesn't have to know it is a list, or an array, or whatever else. Some use it as 'security mechanism' so you can't insert items, but obviously the object can be casted, to not a real solution for that.

  1. return new List {} - is this an anonymous method?

No, it is a collection initializer with two object initializers

  1. Why can't we use list as a return type rather than IEnumerable?

You can.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
0

Q. What is the specific reason we are using IEnumerable here?

When your function return the List it'll be typecasted into IEnumerable, the use of IEnumerable in this case is that: a) Your function will return a read only list. You cannot add or remove anything from the returned collection. b) IEnumerable is the Interface which all the iteratable collection implements. SO basically List is returning the type of Ienumerable which is an example of polymorphism. You can always return IEnumerable if the collection object is implementing it.

Q. return new List {} - is this an anonymous method?

No. This is not anonymous method. This is one of the styles of initializing collection objects and adding values in it.

Q. Why can't we use list as a return type rather than IEnumerable?

You can use List as return type, but in that case the client side which is consuming this method will have an option to add/remove the customers which are being returned. IN case of IEnumerable, the collection will be read only.