False Positive on S1481 in "from" statement where int is required for language syntax

analysers SonarAnalyzer.CSharp 10.7.0.110445

Csharp
S1481

  • Sonar Cloud 2025.1 ,

statement


 from _ in Enumerable.Range(0, items)
                select Task.Run(theTaskAsync)

This is used in short way of doing

  List<Task> tasks= [];
  foreach (int _ in Enumerable.Range(0, items))
  {
      tasks.Add(Task.Run(theTaskAsync));
  }
  return [..tasks];

which the IDE (VS2022) suggest to changing to

        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

Well, the i can be removed of course:

 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.

yes, I forgot to mention the _ did not help, I have edited the original message in case anyone replies without reading your reply

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

Hello @TonyJ and @Corniel

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.