Variable 'fs' hides variable in an enclosing block

17,481

Solution 1

You are declaring the variable, then using that same variable name in a Using block (which tries to declare it again).

Change it to this:

Public Sub CreateScore()
    ' open isolated storage, and write the savefile.
    Using fs As IsolateStorageFileStream = savegameStorage.CreateFile("Score")
    If fs IsNot Nothing Then

        ' just overwrite the existing info for this example.
        Dim bytes As Byte() = System.BitConverter.GetBytes(Scorecount)
        fs.Write(bytes, 0, bytes.Length)
    End If

    End Using

 End Sub

Solution 2

You don't need the Dim fs... line - the Using statement covers the declaration.

The Using statement on its own should be fine as you have it, but if you want to be sure of the typing then change it to:

Using fs As IsolatedStorageFileStream = savegameStorage.CreateFile("Score")
...
Share:
17,481
Charlie Stuart
Author by

Charlie Stuart

Updated on June 08, 2022

Comments

  • Charlie Stuart
    Charlie Stuart about 2 years

    I am currently using the following code:

        Public Sub CreateScore()
        ' open isolated storage, and write the savefile.
        Dim fs As IsolatedStorageFileStream = Nothing
        Using fs = savegameStorage.CreateFile("Score")
        If fs IsNot Nothing Then
    
            ' just overwrite the existing info for this example.
            Dim bytes As Byte() = System.BitConverter.GetBytes(Scorecount)
            fs.Write(bytes, 0, bytes.Length)
        End If
    
        End Using
    
    End Sub
    

    However the fs after using is underlined in blue and gives the error Variable 'fs' hides variable in an enclosing block.

    Does anybody know how i can fix this?

    • Ňɏssa Pøngjǣrdenlarp
      Ňɏssa Pøngjǣrdenlarp over 10 years
      try Using fs As IsolatedStorageFileStream = savegameStorage.CreateFile("Score") and get rid of the DIM statement. you have 2 versions of fs there, but I am not sure that is how ISO works.
    • Idle_Mind
      Idle_Mind over 10 years
      The Using statement will dispose of the variable when the end of its block is reached. Since you've declared it previously, however, the block can't do that. You need to declare that variable in the Using statement itself as Plutonix and Jon Egerton have shown. The fs variable will only be scoped to that Using block then, and therefore it will be safe to be automatically disposed.
  • Douglas Barbin
    Douglas Barbin over 10 years
    The Using statement may or may not be fine as he has it. It won't be if he has Option Infer Off (which I realize is probably unlikely, but we have it off at my office for whatever reason).
  • Jon Egerton
    Jon Egerton over 10 years
    Actually, with "Option Infer Off" he's still (sort of fine): fs would end up typed as "Object", which, while a pain to code against, should still work.