How to: Use 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 Button2.

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

  1. Open a new Windows Application project and place a command button and several other controls on a form named Form1.

  2. Add the following code to the command button's Click event procedure:

    Dim f As New Form1
    f.Show()
    
  3. Run the application, and click the command button several times.

  4. 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

  1. Open a new project, and place a command button on a form named Form1.

  2. From the Project menu, choose Add Class to add a class to the project.

  3. Name the new class ShowMe.vb.

  4. Add the following procedure to ShowMe:

    Public Class ShowMe
        Sub ShowFrm()
            Dim frmNew As Form1
            frmNew = New Form1
            frmNew.Show()
            frmNew.WindowState = FormWindowState.Minimized
        End Sub 
    End Class
    
  5. Add the following code to handle the Click event of Button1 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
    
  6. 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 ShowMe class is created.

See Also

Other Resources

Creating and Using Objects