Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
126 views
Welcome To Ask or Share your Answers For Others

1 Answer

List<T> in C# only has the void Add(T item) method to modify the instance add a single item to the list.

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 ]

list.Append("three");
// list still contains: [ one, two ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...