Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# collection

Tags:

c#

ienumerable

int[] mylist = { 2, 4, 5 };
IEnumerable<int> list1 = mylist;
list1.ToList().Add(1);
// why 1 does not get addedto list1??
like image 731
Learner Avatar asked Dec 06 '25 06:12

Learner


1 Answers

Why would it? ToList() generates a new List and the value '1' gets added to it. Since you don't store the return, the new list then gets tossed when it's out of scope.

ToList() doesn't change the original IEnumerable object list1 or give a new representation (it would be called AsList() if it did).

like image 199
ctacke Avatar answered Dec 07 '25 21:12

ctacke