Home > Refactorings > Refactoring Visual Basic With statements

Refactoring Visual Basic With statements

January 17th, 2012

The With statement (in Visual Basic) is used to execute a series of statements of the particular object without requalifying the name of the object. In other words, we can use the With statement to reduce the number of times we needed to manually type the full path to the target object. For example, this function inverts the background color of the active control of the active form in the current Windows application:

Refactoring With Statement sample code

Using the With statement in this code will look as follows:

Refactoring With Statement sample code result

Inlining the temporary variables will yield into the following code:

Refactor! With Statement Sample code result refactored

Given the choice of creating a With statement for use with an object or a standard initialization, it is recommended to choose the With statement over the usual initialization because it can improve performance and your code will be more efficient. If your code has repeated invocations of a property or a method, the With statement will create a local variable and assign it to the object that you used as an expression of the With statement, so the method or property will only be called once instead of several times on each invocation.

DevExpress Refactor! Pro and CodeRush Xpress has several automatic refactoring operations that allow you to manipulate a With statement without manual code retyping:

Create With Statement

This refactoring creates a With statement for the selected object from the selected code. For example, you can apply the Create With Statement on the code above to automatically create a With statement:

Refactor! Create With Statement preview

It allows you to choose one of the appropriate objects if there are several objects available. The chosen object will be used as an expression of the With statement.

Inline With Statement

This refactoring is the opposite of the Create With Statement refactoring. It allows you to inline the expression of the With statement back into the source code:

Refactor! Inline With Statement preview

It is useful when you want to change the object that is used as the expression of the existing With statement and recreate a With statement that will use a different object.

Split With Statement

This refactoring allows you to automatically split the With statement into two With statements. This is useful when you need to access properties of a parent object that is used inside the expression of the With statement. One With statement will be nested in the other one, for example:

Refactor! Split With Statement preview

Once this refactoring is executed, you can access properties of the parent object as well:

Refactor! Split With Statement result

Products: Refactor! Pro, CodeRush Xpress
Versions: 11.2 and up
VS IDEs: any
Updated: Jan/17/2012
ID: R049

Similar Posts: