Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# list add works but not append? [duplicate]

Tags:

c#

list

append

I'm using C# System.Collections.Generic List and the Add function works as expected but Append does nothing? Why is this? I feel like I'm missing something obvious but I can't see what, I use it the same as Add but it doesn't work?

List<string> x = new List<string>();
x.Add("hello");
foreach (string s in x) { Console.WriteLine(s); }
Console.WriteLine();
x.Add("hi");
foreach (string s in x) { Console.WriteLine(s); }
Console.WriteLine();
x.Append("oi");
foreach (string s in x) { Console.WriteLine(s); }
Console.WriteLine();
x.Append("aye");
foreach (string s in x) { Console.WriteLine(s); }
Console.WriteLine();

output:

hello

hello
hi

hello
hi

hello
hi
like image 651
mizuprogrammer Avatar asked Apr 04 '20 00:04

mizuprogrammer


1 Answers

Append returns the updated collection, instead of modifying the original.

The correct use would be something like var y = x.Append("foo"). Note that you cannot store the result of Append back in x, since it returns a reference of type IEnumerable<string> instead of List<string>.

In general, I would stick with using List<string>.Add(string), unless you are actually dealing with an IEnumerable<T> object.

like image 63
Vera Avatar answered Nov 10 '22 14:11

Vera