In declaration of variables and objects, when exactly should I use "New" word, and when shouldn't I use it? I know that I should declare a string without "New" word:
Dim mystring As String
I also know I should use it declaring a datatable:
Dim mytable As New Datatable()
New
creates an object that is an instance of the specified class. If you just write the following then you have a reference, but the reference is Nothing
as you didn't actually create a Datatable for it to refer to:
Dim mytable As Datatable
You don't typically use New
for value types (Numbers, Dates, Booleans, Structures, Enums - a full list is here), as they always have a value (cannot be Nothing
). For example this outputs 0
:
Dim num as Int32
Console.WriteLine(num)
I wouldn't worry too much about this, but some value types (structures) can be initialised with New
, which is somewhat inconsistent, for example:
Dim dec = New Decimal(2, 3, 4, True, 5)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments