ASP.NET Tip 4. Auto-generating variables in Visual Studio 2010
For more tips like this, LIVE and IN PERSON, come see us at the MSDN Roadshow !
Why declare variables (by hand)? Long gone are the days where no one bothered with Option Explicit or carelessly left variables undefined. It is a common , albeit sometimes tedious, practice to declare variables before assigning values, even if you are doing it all with one line of code. However, for the cases where you want to keep your variable declarations separate; Visual Studio 2010 has an auto-generation feature where you can immediately assign variables, and have VS2010 automatically create the declaration line for you.
Simply type in a line of code that uses a variable that you have yet to declare. Immediately, you’ll see a red squiggly when the design-time background compiler (introduced in VS 2008 SP1) realizes that this variable declaration doesn’t yet exist.
1: blogauthor = "asli";
Simply right click on that squiggly and select Generate—>Field, and Visual Studio will automatically recognize the data type – in this case it recognizes that the value is a String – and will automatically create the declaration for you.
Important note: The declaration will be created at the very end of your code, so if you have a lot of lines of code, it may not show up in your current view pane. Scroll down to the bottom of your code to find the declaration and move it to a correct location. It would be nice to have this generation occur at the top of the file, where typically member variables would belong; although parsing through Using statements and mid-code inserts make it harder to find the declaration.