John Lam 1997 — 2026

Code generation: C# vs. VB.NET

I spent a bit of time today investigating the CIL generated by the VB.NET compiler vs. the CIL generated by the C# compiler. Consider the following VB.NET code:

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

When run through vbc.exe using release settings, this is the CIL that is generated:

.maxstack 2 .locals (int V_0, int V_1, int V_2) L_0000: ldc.i4.3 L_0001: stloc.0 L_0002: ldc.i4.7 L_0003: stloc.2 L_0004: ldloc.0 L_0005: ldloc.2 L_0006: add.ovf L_0007: ret

Consider exactly the same function written using C#:

public int AddThreeAndSeven() { int a = 3; int b = 7; return a + b; }

This is the CIL that is generated:

.maxstack 2 .locals (int V_0, int V_1) L_0000: ldc.i4.3 L_0001: stloc.0 L_0002: ldc.i4.7 L_0003: stloc.1 L_0004: ldloc.0 L_0005: ldloc.1 L_0006: add L_0007: ret

As you can see, the VB.NET code allocates space for an additional local variable that is never used. This is behavior is consistent between debug and release builds. I’m rather surprised by this behavior, but I’m certain that the JIT catches the unused variable and allocates space in the stack frame appropriately.

2 archived reader comments

sara (2003-06-23)

aereawr

**** (2004-04-21)

jghj