Return value of pure method is not used for IEnumerable.ToList()
[6.0.2202]
Code:
NUnit.Framework.TestFixture]
public class TestFixture
{
[NUnit.Framework.Test]
public void Test()
{
int callCount = 0;
new[] {1, 2}.Select(num =>
{
++callCount;
Console.WriteLine(num);
return num;
})
//Without ToList test will fail
//Warning: Return value of pure method is not used
.ToList()
;
NUnit.Framework.Assert.AreEqual(2, callCount);
}
}
Is this by design?
Please sign in to leave a comment.
I gues resharper detects that your LINQ expression it never executed without the ToList call. Select is not doing this if you thought so.
That's the reason for the .ToList(), which is what RS warns for. If I remove .ToList() RS will warn on the Select statement instead (which will, as you say, never be executed).
The warning is because you do not use the result of ToList, the List<int>
We use a custom extension method to run Actions on an IEnumerable so we do not need to use the clunky .Select().ToList() to run an action over every element
Yeah that is one way of doing it (or maybe not), but still, I find the "pure method" warning to be a bit confusing since .ToList() call is actually doing something, just like it does when having a .ForEach extension.
*Edit: Actually I think RS warning is good,it keeps from writing "bad code" (better in that example is to do a foreach loop IMHO). And RS doesn't warn when having an extension method that returns a value that isn'tt used so that seems to work fine as well.
Still curious if this is behavior is by design or not though :).
Seems a perfectly sensible design to me. In most cases, if you're calling ToList without using the returned list, it's an error.
The ForEach extension method, or a simple foreach loop, seems the best approach here. If you're in the anti-ForEach extension method camp, you can just declare it in your test project to avoid polluting your code-base.