This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

VS 2010+

Visual Studio 2010 Generate From Usage

Visual Studio 2010 includes a new code generation feature named Generate From Usage. This allows you to write code that references classes, structures, interfaces, enumerations and members that do not exist and have the IDE create them for you afterwards.

Generating Methods

If an undefined member has parentheses or parameters, you can generate a method stub. Add the following code to the program.

int rotationAngle = 30;
int scalingFactor = 1.2M;
IShape transformed = shape.Transform(rotationAngle, scalingFactor);

If you show the Generate menu or the smart tag for the Transform method in the last line of the code you are given the option to generate a method stub. The new method's code is as follows:

internal IShape Transform(int rotationAngle, decimal scalingFactor)
    throw new NotImplementedException();

Note that the return type of the method has been correctly specified, even though the IShape type does not exist. If the code that the method was generated from used the var keyword, this would need to be changed. As the arguments in the method call were variables, their names are used for the parameters in the new method's signature. If literals had been used in the call, the method's parameters would have default names.

Generating Constructors

You can use the Generate From Code facility to create constructors for classes. To demonstrate, add the code below, which instantiates a Square object using a non-existent constructor.

var shape = new Square(20);

A constructor can be created via the Generate menu or smart tag. In this case, the constructor is generated as shown below. As the argument passed to the constructor was a literal, the name of the parameter is not descriptive so should be changed. The parameter has automatically been assigned to a private field for later use.

private int p;

public Square(int p)
    // TODO: Complete member initialization
    this.p = p;

Generating Enumeration Members

The final item that can be generated from code is an enumeration constant. If you have already defined an enum, you can write code that contains references to undefined enum members. You can then use the Generate menu or smart tag to add the constant to the enumeration. The constant is added as a new item with no explicit value.

1 May 2010