Share via


Debugging and Optimization

The /optimize switch could produce different results when used with Visual C# and Visual Basic .NET Compilers when debugging. If you examine the code in the InitializeComponent method in Calc.vb/Calc.cs, you will notice — just before the loop — that values are set for three variables (x, y, and z). You will also notice that although z is recalculated inside the loop, its value never changes. In fact, z is never referenced again, as shown here (first for Visual Basic):

Private Sub InitializeComponent()
   ...
   Dim j As Integer = 10
   Dim k As Integer = 20
   Dim z As Integer = 0
      
   Dim i As Integer
   For i = 0 To 9
      z = j + k
      btnNumbers(i).Size = New Size(30, 30)
      AddHandler btnNumbers(i).Click, AddressOf btnNumbersClicked
   Next i
...

and then for Visual C#:

private void InitializeComponent() {
   ...
   int j = 10, k = 20, z = 0;
   for (int i = 0; i < 10; i++) {
      z = j+k;
      btnNumbers[i].Size = new Size(30, 30);
      btnNumbers[i].Click += new System.EventHandler(btnNumbersClicked);
   }
...

If you compile this program (and related Parser assembly) with the /optimize switch (using BuildOptimize.bat), set a breakpoint in Calc.cs where the variables are initialized, and step through the program at that point, you will notice something interesting. First, although the statements j=10 and k=20 are both executed, the debugger simply skips over z=0. Then, when executing the loop, the debugger does not stop on the line z=j+k. The effect of the optimization is to remove the code related to variable z, which is never used. Note also that the Locals window does not contain a node for the variable z, as shown in the following figure.

See Also

The Microsoft CLR Debugger | Debugging ASP.NET Web Applications | Appendix A: For Additional Information | Appendix B: Runtime Debugger (CorDbg.exe)