Refactoring Visual Basic With statements
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:
Using the With statement in this code will look as follows:
Inlining the temporary variables will yield into the following code:
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.
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:
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:
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:
Once this refactoring is executed, you can access properties of the parent object as well: