Avatar ·

IEnumerable and List in C#: what to choose and how do they work?

Hi! I'm a beginner in C# and often get confused when I need to choose between IEnumerable and List. For example, I write a method that returns a list of numbers from a database: ```csharp public List GetNumbers() { var numbers = new List(); for (int i = 0; i < 10; i++) { numbers.Add(i); } return numbers; } ``` But my colleague said it's better to return IEnumerable. I don't understand why. Also I noticed that in LINQ methods like Where() return IEnumerable, and ToList() converts it to a List. When I write: ```csharp var query = numbers.Where(n => n > 5); foreach (var n in query) { Console.WriteLine(n); } ``` Everything works, but I don't know what's happening "under the hood". Is there a difference in performance? Can I modify elements in I