Initialization of object variables in VB.Net

Is there a difference in VB.Net between the three following ways to initialize object variables

Method 1

Dim commandObject As SqlCommand commandObject = New SqlCommand("MadeUpCommand") 

Method 2

 Dim commandObject As SqlCommand = New SqlCommand("MadeUpCommand") 

Method 3

 Dim commandObject As New SqlCommand("MadeUpCommand") 

Is they more effective than others, or are they the same anyway?

+4
source share
3 answers

There is no difference in the generated IL between the three methods.

+5
source

Methods 1 and 2 are virtually the same. Method 1, obviously, declares the object in a separate expression for the purpose, but if two lines are next to each other in the code, then it is also actually similar to methods 2 and 3. In this case, I will always use method 3, since it is a required succin. As Darin says, they all generate the same IL.

I would use only method 1, when the declaration and purpose should have different scope, for example. the assignment is performed in the If block, and the value must be checked outside this block.

+1
source

(2) and (3) are equivalent. I hope that (1) will be optimized to be equivalent (even if there are other local variables / instances)

Most of the coding standards I've seen suggest that you have a variable initialized at the declaration point, and also have the declaration point as close to the first as possible.

Of course, in VB.Net 2 and later, I would rather see

  Using commandObject As New SqlCommand("MadeUpCommand") ' Etc. End Using 
+1
source

All Articles