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?
5 comments

I gues resharper detects that your LINQ expression it never executed without the ToList call. Select is not doing this if you thought so.

0

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).

0

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

public static void ForEach<TSource> (this IEnumerable<TSource> source, Action<TSource> action) {
            foreach (TSource element in source) {
                action(element);
            }
}

0

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 :).

0

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.

0

Please sign in to leave a comment.