This article covers the VB.NET With… End With Statement.
Unlike most statements and keywords, the VB.NET With Statement does not offer any new feature or function, at least not in the normal sense. This Statement exists purely to improve readability of your code and saves you some valuable time.
If you’ve had experience with referencing libraries, or maybe while dealing with classes and objects you’ll notice several names chaining together to from some really long names.
With...End With, you can perform a series of statements on a given object, without having to specify the name of the object each time. With-in a
With statement block, you can specify a member of the object starting with a period, as if the
With statement object preceded it.
We’ve created the following class below to help demonstrate the use of the With Statement. We’ve also initialized an object called Person1.
Module Module1 Class Person Public name As String Public age As Integer Public RollNo As String End Class Sub Main() Dim Person1 As Person = New Person() End Sub End Module
We’ll be assigning values to each one of the variables in the Object Person1. First we’ll do so using the regular method.
Person1.name = "Kittens" Person1.age = 15 Person1.RollNo = "123456"
Now, let’s try the same thing, but using the With Statement instead.
With Person1 .name = "Kittens" .age = 15 .RollNo = "123456" End With
As you can see, the With Statements makes our code look cleaner as well as reducing the amount of code we had to write. The difference may seem fairly minimal right now, but in Classes with dozens of variables and especially long named ones, the With statement is a vital asset.
Finally, here’s another example picked from an answer on stack overflow. First is a demonstration without the With statement. The difference between the two will be more apparent here.
UserHandler.GetUser.First.User.FirstName="Stefan" UserHandler.GetUser.First.User.LastName="Karlsson" UserHandler.GetUser.First.User.Age="39" UserHandler.GetUser.First.User.Sex="Male" UserHandler.GetUser.First.User.Occupation="Programmer" UserHandler.GetUser.First.User.UserID="0"
With UserHandler.GetUser.First.User .FirstName="Stefan" .LastName="Karlsson" .Age="39" .Sex="Male" .Occupation="Programmer" .UserID="0" end with
This marks the end of the VB.NET With Statement Article. Suggestions or contributions for CodersLegacy are more than welcome. Any Questions you may have can asked in the comments section below.