New Keyword

  • Thread starter Thread starter Jeff Grundy
  • Start date Start date
J

Jeff Grundy

Is there any difference between these 3 ways of using the
NEW keyword? Which is prefered?

Dim xlApp As New Excel.Application

Dim xlApp As Excel.Application = New Excel.Application

Dim xlApp As Excel.Application
xlApp = New Excel.Application
 
Jeff,
Is there any difference between these 3 ways of using the
NEW keyword?
No


Which is prefered?

I prefer the first one, simply because it's less typing.



Mattias
 
Jeff,

There's no difference between the three examples you gave, but the third
example can lead to more efficient code in the right situations.... Let me
explain:

Say you have an object which takes a long time to create an instance of
(MyReallySlowObject). If you are not 100% sure you are going to use this
object, then you can save this time by only creating it when it is needed.

For example:

Test 1: Wastes time by creating object needlessly if filename is empty
~~~~~~~~~~~~~~~~~~~~~~~~~~
Private Function Test1(Filename as String) as Boolean

Dim objTest as new MyReallySlowObject

' Validate Filename
if Filename.Length = 0 then

' Empty Filename not allowed
return false

end if

' If we get here, do stuff
return objTest.DoStuff(Filename)

End Function

Test 2: Saves time when filename is empty
~~~~~~~~~~~~~~~~~~~~~~~~~~
Private Function Test1(Filename as String) as Boolean

Dim objTest as MyReallySlowObject

' Validate Filename
if Filename.Length = 0 then

' Empty Filename not allowed
return false

end if

' If we get here, do stuff
objTest = New MyReallySlowObject
return objTest.DoStuff(Filename)

End Function


HTH,

Trev.
 
Is New a keyword or is it just the name of the constructor of a VB Class?

Both.

The "New" keyword is used to instantiate an instance of a class and call its
constructor. E.g.:

Dim objTest as New MyClass()


The "New" method is the name of the constructor of the class. E.g.

Public Class MyClass

Public Sub New()

' Do initialization stuff

End Sub

End Class

The new method can be overloaded with different parameters. It can also be
marked with Public, Private or friend scope to control where an instance can
be created from.

HTH,

Trev.
 
You may find that in some circumstances declaring it separately from
instantiating it (New) can be useful. Especially when the constructor takes
arguments that won't be known until later in the code.

Take, for example a streamreader class. You know that you need one, but you
want to verify that the user has supplied a path before you create it.

If you declare the object within the IF statement, it will have "Block
Level" scope and only be available within the IF statement. By declaring it
outside the block, you can use it anywhere else in the procedure.


Dim x as System.IO.StreamReader

If txtFilePath.text <> "" then
x = new System.IO.StreamReader(txtFilePath.text)
End If
 
Back
Top