Udostępnij za pośrednictwem


New (Visual Basic)

Introduces a New clause to create a new object instance, or specifies a constructor constraint on a type parameter.

Remarks

In a type parameter list, a New constraint specifies that the supplied type must expose an accessible parameterless constructor. For more information on type parameters and constraints, see Type List.

In a declaration or assignment statement, a New clause must specify a defined class from which the instance can be created. This means the class must expose one or more constructors that the calling code can access.

You can use a New clause in a declaration statement or an assignment statement. When the statement runs, it calls the appropriate constructor of the specified class, passing any arguments you have supplied. The following example demonstrates this by creating instances of a Customer class that has two constructors, one that takes no parameters and one that takes a string parameter.

' For customer1, call the constructor that takes no arguments. 
Dim customer1 As New Customer()

' For customer2, call the constructor that takes the name of the  
' customer as an argument. 
Dim customer2 As New Customer("Blue Yonder Airlines")

' For customer3, declare an instance of Customer in the first line  
' and instantiate it in the second. 
Dim customer3 As Customer
customer3 = New Customer()

' With Option Infer set to On, the following declaration declares 
' and instantiates a new instance of Customer. 
Dim customer4 = New Customer("Coho Winery")

Since arrays are classes, New can create a new array instance, as shown in the following examples.

Dim intArray1() As Integer
intArray1 = New Integer() {1, 2, 3, 4}

Dim intArray2() As Integer = {5, 6}

' The following example requires that Option Infer be set to On. 
Dim intArray3() = New Integer() {6, 7, 8}

The common language runtime (CLR) throws an OutOfMemoryException error if there is insufficient memory to create the new instance.

The New keyword can be used in these contexts:

Dim Statement (Visual Basic)

Of

See Also

Concepts

Generic Types in Visual Basic

Object Lifetime: How Objects Are Created and Destroyed

Reference

Visual Basic Language Keywords

Type List

OutOfMemoryException

Using Constructors and Destructors

Change History

Date

History

Reason

October 2008

Updated the examples.

Customer feedback.