VS 2010: Generate From Usage

Posted Thu, Apr 1 2010 10:59 by Deborah Kurata

One of the very useful new features in Visual Studio 2010 is the ability to generate a function declaration when writing the code that calls that function. This allows you to define your functions as you need them, but define the implementation details of the function at a later time.

Say you are defining an event and want the event to call a function.

In C#:

image

You have not yet defined this function, so you get a squiggly line under the function. But you also get an option marker (blue underline). Hover over the marker and you get an option icon. Click on the icon and you get code generation options:

image

Click on the option and Visual Studio automatically generates the stub method for ValidateData.

private void ValidateData(bool p)
{
     throw new NotImplementedException();
}

Instead of using the icon, you can right-click on the function name and select Generate | Method Stub to generate the method.

In VB:

image

You have not yet defined this function, so you get a squiggly line under the function. But you also get an Error Correction marker (red underline). Hover over the marker and you get an Error Correction icon.Click on the icon and you get error correction options:

image

Click on the option and Visual Studio automatically generates the stub method for ValidateData.

Private Sub ValidateData(ByVal p1 As Boolean)
    Throw New NotImplementedException
End Sub

Using this technique, your code compiles without having to immediately define the function. The function throws an exception at runtime so you don't forget to add the implementation.

Use this technique whenever you want to write the structure of your code without being interrupted to fill out the implementation details.

This technique is especially useful if you like to follow a test-driven development (TDD) approach where you create the tests before the code.

Enjoy!

Filed under: , , , ,

Comments

# re: VS 2010: Generate From Usage

Thursday, April 01, 2010 2:18 PM by D. Lambert

Deborah -

I love this feature, but I don't think it's new in VS2010.  I'm using it right now in VS2008, unless I'm missing some subtle newness in the VS2010 version.

# re: VS 2010: Generate From Usage

Friday, April 02, 2010 12:24 AM by Deborah Kurata

Hi D. Lambert  -

Thanks for clarifying this. I never noticed this feature in VS 2008, but it is definitely there for C#. (It is NOT in VS 2008 for VB.) The feature has been expanded, however in C# so it also creates classes and  fields.

Thanks again!

# re: VS 2010: Generate From Usage

Friday, April 02, 2010 5:08 PM by Ruddy

Or if you're feeling lazy to use the mouse, you can just hit ctrl + .

and get the same behavior after you see the blue or red marker.

Ruddy

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: