Wednesday, October 26, 2011

Setting Local Variables in Visual Studio

Have you ever wanted to change the value of a local variable inside of a method?  Without changing its code or pausing it in the debugger, that is?  Maybe not, but I did, while writing a unit test this week.  I figured out how to do it in Visual Studio, using Visual Studio's DTE object.  The DTE object provides a programmatic interface to Visual Studio's debugger.  With it, breakpoints can be set and deleted programmatically.  But what about changing the variable?  Breakpoints can have conditions, so...


using EnvDTE;
using System.Runtime.InteropServices;

...

// Get the DTE object.
DTE lDTE =
  Marshal.GetActiveObject( "VisualStudio.DTE" ) as DTE;

// Set a conditional breakpoint.  In this example, the
// break is in file.cs, line 422.
lDTE.Debugger.Breakpoints.Add(
  null,
  "file.cs", 
  422,
  1,
  // Use the break condition to set the local variable
  // you want changed.  Note that the expression always
  // returns false; the debugger will assign 1 to
  // lVariable every time the condition is evaluated,
  // but never pause the unit test.
  "(lVariable = 1.0f).ToString() == null",
  dbgBreakpointConditionType
    .dbgBreakpointConditionTypeWhenTrue,
  null,
  null,
  0,
  null,
  0,
  dbgHitCountType.dbgHitCountTypeNone );

// Call that method...
...

// Delete the breakpoint if you don't want it
// to affect later code.
lDTE.Debugger.Breakpoints.Item( 1 ).Delete();

No comments: