Visual Basic .NET - With statement

The With statement in VB.NET allows you to perform a series of operations on a single object, without having to specify the object name repeatedly. The End With statement is used to terminate the With block. In other words, you can use the With statement to group a set of statements that apply to a single object.

With object
    [statements]
End With

Here, object refers to the object that the statements will operate on. The [statements] within the With block can refer to the object using the . (dot) operator.

Suppose you have a form that contains several TextBox controls, and you want to change the font, foreground color, and background color of each TextBox. You can use the With statement to simplify your code, like this:

With TextBox1
    .Font = New Font("Arial", 12, FontStyle.Bold)
    .ForeColor = Color.Blue
    .BackColor = Color.Yellow
End With
With TextBox2
    .Font = New Font("Times New Roman", 10, FontStyle.Italic)
    .ForeColor = Color.Red
    .BackColor = Color.White
End With
With TextBox3
    .Font = New Font("Verdana", 8, FontStyle.Regular)
    .ForeColor = Color.Black
    .BackColor = Color.Green
End With

In this example, each With block contains a series of statements that apply to a single TextBox control. By using the With statement, you can avoid having to repeat the name of the TextBox control in each statement.

It is worth noting that you can nest With blocks to operate on multiple objects, like this:

With Form1
    .BackColor = Color.Blue
    .Text = "My Form"
    .ClientSize = New Size(300, 200)
    With .MenuStrip1
        .BackColor = Color.White
        .ForeColor = Color.Black
        .Items.Add("File")
        .Items.Add("Edit")
        .Items.Add("Help")
    End With
End With

In this example, the outer With block applies to the Form1 object, and the inner With block applies to its MenuStrip control. Within the inner With block, the Items collection is modified to add three new items.