Reputation: 2787
Is there a difference between the .Append()
and the .Add()
method for lists in C#? I tried searching in Google and in the site but to my surprise no one asked it. My reason for asking is to know if one of the two methods are less performance intensive. I've been using the two methods interchangeably and I didn't see any differences to their function as they both added my object to the end of the list (and this is more or less the description visual studio gives you when you look at the method description).
Edit:
Hmmm I didn't think this mattered at first but I noticed I can use Append on an ASP.NET web application when I can't do that on a console application. So I was asking in the context of an ASP.NET Web App.
Upvotes: 83
Views: 56050
Reputation: 25013
Add
does not return a value: it modifies the original List
.
Append
creates and returns a new sequence, so you can:
var x = new List<int>();
x.Add(1);
x = x.Append(2).Append(3).ToList();
You might like to see Wikipedia:Fluent interface for further information on how chaining functions works.
Upvotes: 30
Reputation: 265155
List<T>
in C# only has the void Add(T item)
method to add a single item to the list by modifying the instance.
IEnumerable<T> Append(this IEnumerable<T> source, T element)
on the other hand is an extension method defined on the IEnumerable<T>
interface (which is implemented by all lists). It does not modify the original list instance, but returns a new enumerable which will yield the specified element at the end of the sequence.
They cannot be used interchangably and behave differently with different outcomes and different side effects. Asking about their relative performance does not make sense as such.
var list = new List<string>();
list.Add("one");
list.Add("two");
// list contains: [ one, two ]
var appended = list.Append("three");
// list still contains: [ one, two ]
appended.ToList(); // appended will yield [ one, two, three ]
Upvotes: 112