Generate From Usage in Visual Studio 2010

Visual Studio 2010 comes with the new Generate From Usage feature.  Let’s take a quick look at how it works.

The basic idea is simple.  You can use classes and their methods and properties before you’ve actually implemented them.  This helps support test-driven development, in which you normally write your test cases first and get them to run by stubbing out all of the actual production code.

Top-Down Design

You might also use the Generate From Usage feature as you implement your code, writing the code in a top-down fashion.  The idea of top-down design is that you start writing your application at the highest level, creating abstractions for all lower-level constructs that are too complex to implement at the highest level.

Generate From Usage Example

Let’s look at an example.  In this example, I have a function that takes some basic info about a book as input and then expects to persist that information in a Book object in a database.  Let’s assume that we haven’t yet created the Book class, or any of its methods or properties.  Then my function might look something like this in Visual Studio:

Notice that since we haven’t yet defined the Book class or any of its methods, Visual Studio underlines the Book identifier with a little red squiggle.

If I hover the mouse over the squiggle, I get a nice error message telling me that Book is not defined.

Now let’s just left-click on the squiggle.  A little blue underline shows up at the start of the unknown identifier.

If you now hover over the blue underline, you’ll see a little smart tag show up.

If you click on the smart tag, you’ll see two options: Generate class for ‘Book’ and Generate new type…

The simplest thing to do at this point is to select the first option, to generate a new Book class.  If we pick that option, a Book.cs file will be automatically added to our project, with a skeleton implementation of the Book class.

namespace WpfApplication3
{
    class Book
    {
    }
}

Notice, however, that focus stays in the original code editor window, so you can continue working in the same place.  At this point, the red squiggle on the Book class has disappeared, since we now have a basic implementation of the class.  Also notice that we see a whole bunch of new squiggles.  Now that Book is a valid class, Visual Studio knows that it does not contain any of the properties or methods that we are referencing.

Detour–Generate New Type

Let’s go back a step.  What would have happened if we’d selected the Generate new type… option?  Let’s try it.  If you pick this option, you’ll get a dialog asking you to enter some more details on the class that you want to create.

Basically, you can choose this option if you want to specify some additional details about the class that you want to create, including the file name, which project to create it in, and the access modifier for the class.  You can also have Visual Studio create other constructs, like a struct or an interface.

Return From Detour

Now let’s go back to the EnterBook() method that we were working on.  Remember that after we generated the Book class, we got a bunch more squiggles.  As before, if you hover over the squiggle, you’ll see what the error is.  For example, we didn’t add a non-default constructor to the Book class, so we’re seeing an error when we try to construct the object.

Once again, we can use the Generate From Usage feature to generate some code for us.  As before, click on the squiggle and then click on the smart tag.  Now we see an option to generate the constructor.

Once again, if you click on this option, nothing will appear to happen in the code window where you are working.  But if you open the Book class, you’ll see that it now has a new constructor.

class Book
{
    private string Title;

    public Book(string Title)
    {
        // TODO: Complete member initialization
        this.Title = Title;
    }
}

But notice that Visual Studio went even one step further.  It also created a private field named Title for us and set the value of the field to the book title that we passed into the constructor.  This is (almost) exactly what we want.  (Likely, we’ll want to convert the private field into a property).

Encapsulating a Field

Actually, since I mentioned it, let’s go ahead and convert this field to a property.  First, I’ll rename the field, from “Title” to “_title”.  I do this because I’m going to want my property to be named Title.  So I want my backing variable (the existing field) to be named something else.  Now just right-click on the field, select Refactor and then select Encapsulate Field.

You’ll then get a dialog asking you to confirm the name of the field.

Click OK and then go back to look at your new code in the Book class.

class Book
{
    private string _title;

    public string Title
    {
        get { return _title; }
        set { _title = value; }
    }

    public Book(string Title)
    {
        // TODO: Complete member initialization
        this._title = Title;
    }
}

Perfect!

Generating a Property Stub

Now let’s go back to our EnterBook function again and once again click on a smart tag.  This time, click on the tag for the line where we’re trying to set the LastName property.  You’ll see the following:

Notice that we’re always seeing options that are appropriate for the type of object that is undefined.  In this case, Visual Studio sees that we are using LastName as a property, so it offers to create it for us.

If you select the option to generate a property stub, rather than a field stub, you’ll get what you expect in your Book class:

    public string LastName { get; set; }

Visual Studio created a new property named LastName and automatically generated the get and set accessors for the property.  Also notice that it figured out the correct type for the property, based on the variable that we were assigning to it.

Generating a Method

We’ll do just one more example.  As expected, if you click on the smart tag at the point where we’re trying to call a Save method, Visual Studio will offer to generate the method.

As you’d expect, Visual Studio once again generates a stub in the Book class for us:

    internal void Save()
    {
        throw new NotImplementedException();
    }

Wrapping Up

There you have it–a quick tour through the new Generate From Usage feature in Visual Studio 2010.  Once you get into the habit of using it, you can be quite a bit more productive when coding in a top-down fashion.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s