When "As New" or not when instantiating?

  • Thread starter Thread starter Ronald S. Cook
  • Start date Start date
R

Ronald S. Cook

So most of the time I need to write the following to instantiate an object:

Dim cnn As New SqlConnection()

But sometimes Intellisense tells me not to include the "new":

Dim dst As DataSet

When do I use "As New" and when don't I? Intellisense is good at letting me
know which is correct, but I'd like to understand better.

Thanks,
Ron
 
If you might not need the object right away, or possibly might not need
it at all, or if you need a broader scope, then just

Dim dst As DataSet

Otherwise, if you need it right away and you will be throwing it out immediately when you're done with it, use New.

Tom
 
Ronald,

If you create a New dataset than you use the keyword New

dim ds as New Dataset
dim dt as New DataTable
ds.Tables.Add(dt)

dim ds as New Dataset
da.Fill(ds) 'it is filled not created.

However if you use the ds as a placeholder to put an object in, than you
create of course no New dataset.

dim ds as Dataset = MyOldDataset.Copy

I hope this helps,

Cor
 
Dim Myvar as New Whatever - creates a variable Myvar, creates a new
Whatever, and sets myvar to reference Whatever.

Dim Myvar as Whatever - creates a variable myvar that can reference a
Whatever, but doesn't actually create a new Whatever, so Myvar
initially references Nothing. You can set Myvar to an instance of
Whatever later, for example Myvar = New Whatever, or Myvar =
SomeOtherExistingWhatever.

Some object types you cannot create a New instance of directly, they
can only be created through other objects. Indeed, Intellisense warns
you about that.
 
Ronald S. Cook said:
So most of the time I need to write the following to instantiate an
object:

Dim cnn As New SqlConnection()

But sometimes Intellisense tells me not to include the "new":

Dim dst As DataSet

When do I use "As New" and when don't I? Intellisense is good at letting
me know which is correct, but I'd like to understand better.

Dim x as Gizmo
this creates a variable named x that can reference an object of type Gizmo
at this point, however, x does not reference an object (its a null pointer)
x = new Gizmo()
this calls the constructor of the Gizmo class and now the variable x
references an object of type Gizmo.
the sub named new 'instantiates' an object of the class.
HTH
 
Back
Top