tags:

views:

151

answers:

3

In VB.Net is there any difference between the following three ways of initialising 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 one more efficient than the others, or are they effectively all the same?

+3  A: 

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

Darin Dimitrov
+1  A: 

Methods 1 and 2 are effectively the same. Method 1 obviously declares the object in a seperate statement to the assignment, but if the 2 lines are next to each other in code then it is also effectively the same as methods 2 and 3. In this case I would always use method 3 as it is the must succint. As darin says, they all generate the same IL.

I would only use method 1 when the declaration and assignment are required to have different scope, e.g. the assignment is done within an If block and the value needs to be tested outside that block.

AdamRalph
A: 

(2) and (3) are equivalent. I'd hope (1) gets optimised to be equivalent too (even if there are other local variables/instantiations)

Most coding standards I've seen suggest having the variable initialised at the point of declaration, and also having the point of declaration as close as possible to first use.

Of course, in VB.Net 2 and later, I'd prefer to see

    Using commandObject As New SqlCommand("MadeUpCommand")
        ' Etc.
    End Using
Rowland Shaw