zeroin23
zeroin23

Reputation: 1821

Vb.net declaration and initialization

Is there any difference between these 2 ways of declaring and initialization ?

Dim con as New OracleConnection(connstr)
con=Nothing

Dim con as OracleConnection
con=New OracleConnection(connstr)
con=Nothing

Update: Dim con as OracleConnection = New OracleConnection(connstr)

Is equivalent to ?

Upvotes: 0

Views: 1531

Answers (2)

John Woo
John Woo

Reputation: 263703

They have no differences. But you can still simplify your declaration

Using con As New OracleConnection(connstr)
   ' other codes here
End Using

The Using statement automatically disposes the object after it has been used.

SEE also here

UPDATE 1

this one allocates memory directly because of the NEW keyword:

Dim con as New OracleConnection(connstr)   ' declaration and allocating in the memory
con = Nothing                              ' disposes the object

this does not allocate the memory until the NEW keyword is supplied.

Dim con as OracleConnection          ' declaration only
con = New OracleConnection(connstr)  ' allocates memory
con = Nothing                        ' disposes the object 

Upvotes: 1

Dai
Dai

Reputation: 155065

VB's Dim foo As New bar is syntactic sugar and shorthand for:

Dim foo As Bar
foo = New Bar()

It's VB's equivalent to C#'s var keyword in this sense (except without compiler type inference):

var foo = new Bar();

Note that you don't need to set local variables to Nothing in VB after you're using them as they will automatically be disposed/finalised after they fall out of scope. Preemptively setting variables to Nothing is a idomatic habit from VBScript where you needed to nullify COM objects to decrement their Reference-count so they would be disposed, you don't need to do it in VB.NET.

Upvotes: 1

Related Questions