Friday, January 2, 2009

Unused Local Variable

I recently ran into an interesting quirk (not sure if I even want to call it that) in Visual Studio. Here is a piece of code that demonstrates the quirk:

Sub Main()
Dim a As Integer
a = 1

Exit Sub

Dim b As Integer
b = 1
End Sub

If you paste this into Visual Studio you will notice that you get a squiggly under the ‘b’ variable with an warning that says Unused Local Variable. I first encountered this in a much large function I was developing and it drove me crazy for a while until I realized that it was the Exit Sub earlier in the code that was causing it. Obviously you would never do this in production code but I had inserted the Exit Sub for debugging purposes.
This quirk was interesting to me because VS was obviously smart enough to know the b=1 would never be executed but didn’t take into account the fact that it would never even be declared. You can get some more insight into this by looking at the IL disassembly for the code:
.method public static void  Main() cil managed
  .custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) 
  // Code size       3 (0x3)
  .maxstack  1
  .locals init ([0] int32 a,
           [1] int32 b)
  IL_0000:  ldc.i4.1
  IL_0001:  stloc.0
  IL_0002:  ret
} // end of method Module1::Main

You can see in the IL that both local variables a and b are declared before that start of the code. You will also notice that nothing after the Exit Sub gets compiled, the assignment of b does not show up in the IL. So the behavior we see in VS is consistent with what we see in the IL, b is defined but never used.


Anonymous said...

Nice brief and this enter helped me alot in my college assignement. Gratefulness you on your information.

Bondscoach said...

Thanks, that helped!