Using the New Keyword
To create an instance of a class, use the New keyword. Unlike value types, such as Integer and Double, objects are reference types, and you must explicitly create them before you can use them. For example, consider the following two lines of code:
Dim Button1 As System.Windows.Forms.Button
Dim Button2 As New System.Windows.Forms.Button()
The first statement declares an object variable that can contain a reference to a button object. However, the variable
Button1 contains the value Nothing until you assign an object of type Button to it. The second statement also defines a variable that can contain a button object, but the New keyword creates a button object and assigns it to the variable
Because forms and controls are actually classes, you can use the New keyword to create new instances of these items as needed.
To create new instances of a class with New
- Open a new Windows Forms project and place a command button and several other controls on a form named
- Add the following code to the command button's Click event procedure:
Dim f As New Form1 f.Show
- Run the application, and click the command button several times.
- Move the front form aside. Because a form is a class with a visible interface, you can see the additional copies. Each copy has the same controls, in the same positions as those on the original form at design time.
You can use the New keyword to create objects from within classes. The following procedure provides an example.
To see how New creates instances of a class
- Open a new project, and place a command button on a form named
- From the Project menu, choose Add Class to add a class to the project.
- Name the new class
- Add the following procedure to
Public Class ShowMe Sub ShowFrm() Dim frmNew As Form1 frmNew = New Form1 frmNew.Show() frmNew.WindowState = 1 End Sub End Class
- Add the following code to the Button1_Click event of the button on your form:
Protected Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim clsNew As New ShowMe() clsNew.ShowFrm() End Sub
- To use the example, run the application and click the command button several times. A minimized form icon appears on your taskbar as each new instance of the
ShowMeclass is created.