Title | Declare variables in VB .NET |
Keywords | variable, VB .NET, initialization, declaration |
Categories | VB.NET |
|
|
VB 6 style variable declarations still work in VB .NET.
|
|
Dim x As Single
Dim txt As String
|
|
VB .NET also allows you to initialize variables in the declaration.
|
|
Dim x As Single = 1.23
Dim txt As String = "VB Helper Rules!"
|
|
You can initialize object variables using either a "As New Class" or "As Class = New Class" syntax.
The first version is more concise and seems a bit easier to read so it's generally preferable.
Note that the String data type is actually a class so you can use these methods to declare strings.
|
|
Dim txt1 As New String("VB Helper Rules!")
Dim txt2 As String = New String("VB Helper Rules!")
|
|
When you use these methods to initialize an object variable, you are invoking one of the object's constructors.
Different constructors use different arguments to initialize the object. For example, the following declaration
initializes a String with the value **********. This declaration uses a String constructor that takes as
parameters a character (the syntax "*"c means a character * [as opposed to a string]) and a number. It initializes the String to
contain the indicated number of repetitions of that character.
|
|
Dim txt3 As New String("*"c, 10)
|
|
Sometimes you might want to create a variable without giving it a name in its own declaration.
For example, the following code draws a blue line in a form's Paint event handler. The variable e is the
event handler's event object. It's Graphics property provides methods for drawing on the form.
The interesting part here is the way the code initializes a new Pen object without creating a variable for it.
It is used and then discarded.
|
|
e.Graphics.DrawLine(New Pen(Color.Blue), 0, 0, 100, 100)
|
|
Related topics:
|
|
-->