I am using Resharper 2018.1.3 (I updated to 2018.2.0 and I experienced the same issue) with Visual Studio 2017.
When I type this code:
var test = new List<string>();
var strings = new[] { "a", "b", "c" };
foreach (var a in strings)
{
test.Add(a);
}
Resharper suggests to convert it into LINQ-expression.
But if I use a List
:
var test = new List<string>();
var strings = new List<string> { "a", "b", "c" };
foreach (var a in strings)
{
test.Add(a);
}
Resharper gives me no hint. Why?
While in this particular case the transformation to LINQ looks safe, in general it can have unexpected side effects. System.Collections.Generic.List
has a special implementation of GetEnumerator
method which returns a struct. LINQ methods works with IEnumerable
where GetEnumerator
methods return instance of interface IEnumerator
. So, converting foreach
to LINQ can cause undesired boxing.
In some cases GetEnumerator
method used by foreach
and implementation of IEnumerable.GetEnumerator
can return completely different Enumerator
s like we have in IDictionary
where GetEnumerator
enumerates over DictionaryEntry
s while implementation of IEnumerable.GetEnumerator
iterates over objects which are actually instances of KeyValuePair
in case of System.Collections.Generic.Dictionary
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.