Why IEnumerable<T>.Reverse()
returns the reversed collection with the original collection and List<T>
reverses the original collection itself? This is somewhat confusing to me since List<T>
inherits from IEnumerable<T>
.
Conceptually, this may be because IEnumerable
is used when you want to represent an immutable collection of items. That is, you only want to read the items in the list, but not add/insert/delete or otherwise change the collection. In this view of the data, returning a new IEnumerable
in a different order is the expected result. When you use a List
, you expected to be able to add/insert/delete or otherwise mutate the collection, so a Reverse
method that changes the order of the original list would be expected in that context.
As others have noted IEnumerable
is an interface and List
is a class. List
implements IEnumerable
.
So,
IEnumerable<String> names = new List<String>();
var reversedNames = names.Reverse();
gets you a second list, reversed. Whereas,
List<String> names = new List<String>();
names.Reverse();
Reverses your original list. I hope this makes sense.