2

I am getting undeclared variable errors with my code and I don't know why! The variables are declared above, but when being used, they are not found! The error in question occurs on the variables with two stars

    If hour >= 10 Then
        Dim hourAnn = My.Resources.ResourceManager.GetObject("_" + hour.ToString)
    Else
        Dim hourAnn = My.Resources.ResourceManager.GetObject("_0" + hour.ToString)
    End If

    If minute >= 10 Then
        Dim minuteAnn = My.Resources.ResourceManager.GetObject("_" + minute.ToString)
    Else
        Dim minuteAnn = My.Resources.ResourceManager.GetObject("_" + minute.ToString)
    End If

    'Ann Type
    If annType = 1 Then
        My.Computer.Audio.Play(My.Resources.nowApproachPlatform, AudioPlayMode.WaitToComplete)  'The train now approaching platform
        My.Computer.Audio.Play(platformAnn, AudioPlayMode.WaitToComplete)                       'x
        My.Computer.Audio.Play(My.Resources.isThe, AudioPlayMode.WaitToComplete)                'is the
        My.Computer.Audio.Play(**hourAnn**, AudioPlayMode.WaitToComplete)                '<hour>
        My.Computer.Audio.Play(**minuteAnn**, AudioPlayMode.WaitToComplete)                '<min>
2
  • 2
    I cant see any stars, but an If statement creates a new block scope, so hourAnn and minuteAnn go out of scope immediately after they are declared Apr 28, 2016 at 16:08
  • Stars are in the If statement at the bottom :)
    – user4838695
    Apr 28, 2016 at 16:13

1 Answer 1

4

Variables are only known in the scope they are created.

If you create a variable in an if-structure, they are only known inside that if. Same counts for functions, for-loops and any other "containing" structures.

Solution for your code:

Dim hourAnn = ""
 If hour >= 10 Then
        hourAnn = My.Resources.ResourceManager.GetObject("_" + hour.ToString)
    Else
        hourAnn = My.Resources.ResourceManager.GetObject("_0" + hour.ToString)
    End If

Dim minuteAnn = ""
If minute >= 10 Then
    minuteAnn = My.Resources.ResourceManager.GetObject("_" + minute.ToString)
Else
    minuteAnn = My.Resources.ResourceManager.GetObject("_" + minute.ToString)
End If

Want to learn more? Read here

2
  • 1
    @DavidWheatley Please consider marking my answer as "the answer" and upvote it, if it helped you.
    – Jordumus
    Apr 28, 2016 at 16:10
  • 1
    I have to wait a few minutes first, it won't let me right away!
    – user4838695
    Apr 28, 2016 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.