Tuesday, December 05, 2006

In one of my articles I have written about using Immediate Window for debugging purposes - how we can use this Window to debug an application without starting it. Basically you can use the Window, to start a debugging process on any of your methods just by invoking it in Immediate Window:

new MyNamespace.MyType().MyMethod()

or for static methods just

MyNamespace.MyType.MyMethod()

There are however other useful features that make this window even more powerful.

One of them is evaluation of commands. Take for example:

System.Guid.NewGuid()
{04653f8d-58d3-4254-adc8-fb6d95457b49}

Which presents you with a new Guid instance as a string. Nice feature to have since I'm no longer able to find the Generate Guid window in my Visual Studio 2005. This window was very useful when I was working with Visual Studio 2003.

The above is simply a static method call. Lets see what else can we do. The immediate window can be used as a simple (or very advanced when you think about it) calculator. Take for example:

5*5
25

What we get in return is... of course the result of this operation. Still this is also a method call underneath. We can go very far with this, as far as the .NET classes allows us to. If we need an advanced calculator we can use some of the Math's methods:

System.Math.Sqrt(4) + 3.2
5.2

Those are still only simple method calls. The interesting part begins with multi-line statements!

The immediate window allows commands to span multiple lines and include variables. With those you can do almost anything you could do in the normal code:

int x = 2;
2
int y = 3;
3
x + y
5

If you wonder how far you can go with Immediate Window, just consider this example:

System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection("someconnectionstring");
System.Data.SqlClient.SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM SomeTable";
connection.Open();
System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
reader[0];

Not that you will use the window for such commands, but it is nice to know what it can really do :-)

BTW: I have noticed that sometimes Visual Studio hides the Immediate Window from me. While doing so it also removes the one place in the menu that I know of that can be used to show the window: Debug->Windows->Immediate. If your Visual Studio also knows better, the shortcut Ctrl+Alt+I will help you.

kick it on DotNetKicks.com