views:

42

answers:

2

I'm working with LINQ in VB.NET and sometimes I get to a query like

For i = 0 To 10
  Dim num = (From n In numbers Where n Mod i = 0 Select n).First()
Next

and then it comes the warning "Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable."

I know it's not a good practice to use the iteration variable in the lambda expression, because lambda expressions are evaluated only when needed. (This question is about that)

Now my question is, how to suppress this warning in cases where the expression is evaluated in-place, with constructions like First(), Single(), ToList(), etc. (It's only a warning, but i like my code clean.)

(Declaring a local variable and passing the iteration variable to it is an option, but I'm looking for somthin else.)

A: 

You could suppress the warnings via projects settings or compiler directives like:

#pragma warning disable 42327
...your code
#pragma warning restore 42327

42327 is the error number of the "Using the iteration variable..."-warning

Also you could edit your project file (.vbproj) add add the error number to the NoWarn-XmlTag

I would not recommend that, but always use a local variable

Edit: VB.Net doesn't seem to support the pragma-directive

dkson
+1  A: 

In this particular case where the lambda is evaluated immediately, then you can safely eliminate the warning by moving the declaration of the iteration variable outside the for loop.

Dim i = 0
For i = 0 To 10 
 ...

I do want to stress though that this only works if the lambda does not escape the for loop (true for your scenario).

Also here is a detailed link to an article I wrote on this warning (why it exists, how to avoid it, etc ...)

JaredPar
Thanks, that's an option too. (It's not the best, but maybe there isn't a best option for this solution)
jaraics