-1

Let's suppose I have a method like this:

public IEnumerable<string> GetList()
{
   var list = new List<string>()
   {
      "1",
      "2"
   };

   return list;
}

The method returns an IEnumerable<string>, in the method though I return a List, because the List derives from IEnumerable (wrong word I guess, correct me if I'm wrong) this is possible.

But when I use the returned value in another place such as:

var returnList = GetList();

Now, returnList is a IEnumerable and that's totally fine.

My questions are:

  1. Is the value converted into IEnumerable when I return it as a List in the method?
  2. If there is, does this conversion slow down the general program, just like ToList() does?
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Steve
  • 47
  • 6

2 Answers2

1

There's no conversions being done, IList<> already implements (or in other words, already is) IEnumerable<>. What you get out of your function is exactly the list you send and nothing stops the caller from getting back a variable of type List<> out of it again.

Blindy
  • 65,249
  • 10
  • 91
  • 131
0
  1. No. IEnumerable<T> is an Interface. List<T> implements the IEnumerable<T> interface. Anything that implements a given interface can be used as if its type is the interface.
  2. There is no conversion.
Jonathan Dodds
  • 2,654
  • 1
  • 10
  • 14