Shadowing through Scope

  • Thread starter Thread starter sougata12
  • Start date Start date
S

sougata12

Guest
Hi,

Following is the piece of code I wrote.

Module Module1
Public temp As Integer = 42
Sub printTemp()
Console.WriteLine("TEMP from sub printTemp: {0}", temp)
End Sub
Sub Main()
Dim temp As Integer = 2
Dim constant As Integer = 1
Do While constant <= 10
Dim temp As Integer = 25 'Error comes here
Console.WriteLine("{TEMP from Do_While: {0}", temp)
constant += 1
Loop
Console.WriteLine("TEMP from sub Main(): {0}", temp)
printTemp()
Console.ReadLine()
End Sub
End Module


The error I am getting is as follows:

1510734.png


My Question:

I read that when shadowing happens through scope the compiler resolves to the variable with the narrowest scope. This was the reason I had declared the variable TEMP inside the Do-While block (since block scope is the narrowest..and I wanted to test that). However I get an error as shown above. Can someone please explain why the error is coming? I can declare some other new variable inside the Do-While block but not TEMP. I can understand that it has something to do with the statement Dim temp as Integer = 42 - just after sub Main() but not able to pin point the reason clearly. Can someone pls help?












Sougata Ghosh

Continue reading...
 
Back
Top