Search code examples
vb.netforeachcrystal-reportsvb6

Variable will not be inferred because it is bound to a field in an enclosing scope?


I'm rewriting a VB6 app to VB.net, and have come across this error:

The type for variable "crxTable" will not be inferred because it is bound to a field in an enclosing scope.

I have this code:

Private crxTable as CRAXDRT.DatabaseTable

For Each crxTable in crRep.Database.Tables
   'do stuff
Next

From what I understand, the error occurs because crxTable is essentially used twice, which leads me to ask:

What is the better approach? To use a different name in the For Each, such as table, or to use the fully qualified name - Me.crxTable / MyBase.crxTable? What's the difference between the two?


Solution

  • It's better to use a different name to avoid this warning and to avoid issues which could arise if someone forgets/doesn't know that the loop in this method modifies the field.

    So i would use this:

    Private CRX_Table As CRAXDRT.DatabaseTable
    
    ' ..... '
    
    For Each crxTable As CRAXDRT.DatabaseTable In crRep.Database.Tables
       'do stuff
    Next
    

    If you can omit the As CRAXDRT.DatabaseTable in the For Each-loop depends on whether crRep.Database.Tables returns a strongly typed collection or not.

    Note that you could avoid the warning also by providing the type yourself with As:

    Private crxTable As CRAXDRT.DatabaseTable
    
    ' ..... '
    
    For Each crxTable As CRAXDRT.DatabaseTable In crRep.Database.Tables
       'do stuff
    Next
    

    Now you dont get a warning but the code is still dangerous. The value of the field crxTable changes on every iteration of the loop. So it stores only the last CRAXDRT.DatabaseTable of all tables. I wouldn't use the field in a loop. Period.