tasks.AddRange(from int _ in Enumerable.Range(0, items)
select Task.Run(theTaskAsync));
The _ is however identified as an unused variable, but can’t be removed from the statement, replacing by _ still gives the same warning
other examples from utest set up code
var random = new Random(0);
var insts = from _ in Enumerable.Range(0, 1000)
let instId = random.Next(1, 500)
let subInst= random.Next(1, 4)
select (instId , subInst);
the _ is needed to iterate the loops, but is not needed in the statement
the problem also exists with i , which is not signalled as an unused variable when in a for loop
public async Task Run(int items)
{
var selection =
from _ in Enumerable.Range(0, items) // FP: S14818 should not report on _
select Task.Run(AsyncTask);
}
private static async Task AsyncTask() { }
However, S1481 also reports on the _, which it should not do.
@TonyJ I think that the fact that it reports on i is not a FP, but that is reports on _ is. I’m looking forward to a response of someone of the Sonar team.
agreed, I further modified the original post to avoid debate
interesting however is that use of an unused variable i here
List<Task> tasks= [];
foreach (int _ in Enumerable.Range(0, items))
{
tasks.Add(Task.Run(theTaskAsync));
}
return [..tasks];
does not trigger an used variable warning for i.
We do not track loop variables and therefore the foreach loop does not raise S1418. On the other hand, we should not raise on any variables named _ as they are often used to signal a discard and as such is expected to be unused.
I created a re-producer and issue for the _ in our internal backlog.