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.
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.
The common language runtime (CLR) throws an OutOfMemoryException error if there is insufficient memory to create the new instance.
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: