Runtime: IList-Reverse bug

Created on 24 Apr 2017  路  4Comments  路  Source: dotnet/runtime

IList test = new List() {0, 4, 9};
test.Reverse(); //it's failure

area-System.Collections question

Most helpful comment

This should work:

C# IList<int> t = new List<int>{0,4,9}; foreach (var item in t.Reverse()) { Console.WriteLine(item); }

  • List<T>.Reverse() actually mutates the list.
  • IList<T> doesn't have a Reverse() method, you're calling Enumerable.Reverse() which returns a reversed IEnumerable<T> but doesn't change the underlying list. That's likely what you're running into.

It's a pretty common problem people hit http://stackoverflow.com/questions/12390971/why-there-is-two-completely-different-version-of-reverse-for-list-and-ienumerabl.

All 4 comments

Works just fine for me:

Microsoft (R) Roslyn C# Compiler version 2.1.0.61520
Loading context from 'CSharpInteractive.rsp'.
Type "#help" for more information.
> var t = new List<int> { 0, 4, 9 };
> t.Reverse();
> t
List<int>(3) { 9, 4, 0 }
> 

I declare the t: IList. IList t = new List{0,4,9};
So try this. Thank you!

IList<int> t = new List<int>{0,4,9}

This should work:

C# IList<int> t = new List<int>{0,4,9}; foreach (var item in t.Reverse()) { Console.WriteLine(item); }

  • List<T>.Reverse() actually mutates the list.
  • IList<T> doesn't have a Reverse() method, you're calling Enumerable.Reverse() which returns a reversed IEnumerable<T> but doesn't change the underlying list. That's likely what you're running into.

It's a pretty common problem people hit http://stackoverflow.com/questions/12390971/why-there-is-two-completely-different-version-of-reverse-for-list-and-ienumerabl.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

btecu picture btecu  路  3Comments

jchannon picture jchannon  路  3Comments

nalywa picture nalywa  路  3Comments

matty-hall picture matty-hall  路  3Comments

GitAntoinee picture GitAntoinee  路  3Comments