Difference between Add and Append methods of a list in C#

12 April 2023 | Viewed 4157 times

List.Add()

Add method will modify the instance of the list and adds a single item to the end of the list. This methods will not return anything.

C# Code
//syntax
void List<T>.Add(T item)

//ex:-
List<string> list = new List<string>{ "ADF", "App Services" };
list.Add("Function App");

//output
//{ "ADF", "App Services", "Function App" }

In the above example "Function App" will be added at the end of the list.

IEnumerable.Append()

Append is an extension method defined on the IEnumerable<T> interface. 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.

C# Code
//syntax
IEnumerable<T> IEnumerable<T>.Append(T item)

//ex:-
List<string> listA = new List<string>{ "Azure", "iCloud" };

List<string> listB = listA.Append( "AWS" );

//output of List A will remain same
//{ "Azure", "iCloud" }

//output of List B will contain appended item
//{ "Azure", "iCloud", "AWS" }


PreviousNext