John Lam 1997 — 2026

Update on VB.NET code generation

Thanks to Scott Ellis who wrote in to explain why VB.NET is generating the extra local variable in a function declaration. It’s due to the fact that you can assign the return value of the function to the name of the function in VB.NET. Scott sent along the following code snippet that illustrates the usage of the extra local:

Public Function AddThreeAndSevenAsn() As Integer Dim a As Integer = 3 Dim b As Integer = 7 AddThreeAndSevenAsn = a + b End Function

When you disassemble this function using ILDASM, you’ll get the following:

.method public instance int32 AddThreeAndSevenAsn() cil managed { // Code size 11 (0xb) .maxstack 2 .locals init ([0] int32 a, [1] int32 AddThreeAndSevenAsn, [2] int32 b) IL_0000: nop IL_0001: ldc.i4.3 IL_0002: stloc.0 IL_0003: ldc.i4.7 IL_0004: stloc.2 IL_0005: ldloc.0 IL_0006: ldloc.2 IL_0007: add.ovf IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ret } // end of method Class1::AddThreeAndSevenAsn

This totally makes sense to me now.