Recipe 3.5. Creating Object Instances


Problem

You need to create an instance of a class or structure.

Solution

Use the New keyword to create a new class or structure instance.

Discussion

There are three basic places you use the New keyword:

  • When you declare a new instance of a type. The Dim statement offers a few different variations when using the New keyword. Both of the following examples create a new instance of a project-specific Employee class. Other than the minor syntax differences, the two lines are functionally identical:

     Dim someEmployee As New Employee Dim someEmployee As Employee = New Employee 

  • When you assign new instances to existing variables. Once you have a variable defined, you can assign it an instance using New:

     Dim someEmployee As Employee someEmployee = New Employee 

  • In-line, whenever you need an instance that you don't capture in a variable. Sometimes you simply need a class to exist only within a statement, perhaps as an argument to another function. This is quite common when working with GDI+ graphic elements, such as pens. The following code block draws a line on a form during its Paint event. It creates a new Pen object that disappears once the call to DrawLine() ends:

     Private Sub Form1_Paint(ByVal sender As Object, _       ByVal e As System.Windows.Forms.PaintEventArgs) _       Handles Me.Paint    e.Graphics.DrawLine(New Pen(Color.Red), 0, 0, 100, 100) End Sub 

All three uses of New can be intermixed within the same block of code, and you can choose what best fits the needs and logic of the code block.

See Also

The New keyword is also used in a different context to create class constructors. See Recipe 3.6 for additional details.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net