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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With