Udostępnij za pośrednictwem


New Operator (Visual Basic)

Introduces a New clause to create a new object instance, specifies a constructor constraint on a type parameter, or identifies a Sub procedure as a class constructor.

Remarks

In a declaration or assignment statement, a New clause must specify a defined class from which the instance can be created. This means that 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.

Note

The New keyword is also used in type parameter lists to specify that the supplied type must expose an accessible parameterless constructor. For more information about type parameters and constraints, see Type List (Visual Basic).

To create a constructor procedure for a class, set the name of a Sub procedure to the New keyword. For more information, see Object Lifetime: How Objects Are Created and Destroyed (Visual Basic).

The New keyword can be used in these contexts:

Dim Statement (Visual Basic)

Of Clause (Visual Basic)

Sub Statement (Visual Basic)

See Also

Reference

Type List (Visual Basic)

OutOfMemoryException

Concepts

Generic Types in Visual Basic (Visual Basic)

Object Lifetime: How Objects Are Created and Destroyed (Visual Basic)

Other Resources

Keywords (Visual Basic)