user1447679
user1447679

Reputation: 3240

Declaring multiple variables in vb.net, With one "Dim" or multiple, what's the difference?

Simple question, hopefully a simple answer.

What's the difference between:

Dim something As String = "Hello"
Dim somethingElse As String = "World"
Dim putittogether As String = something & " " & somethingElse

And

Dim something As String = "Hello",
    somethingElse As String = "World",
    putittogether As String = something & " " & somethingElse

I'm aware of typical multiple declarations like...

Dim start, end As DateTime

More curious about my first and second example, benefits, no benefits? Doesn't matter?

Upvotes: 1

Views: 1652

Answers (1)

SSS
SSS

Reputation: 5403

Just for fun, I ran both versions through ILDASM to see if there was any difference after compilation. As you can see, there is no difference at all in the output IL.

First example - separate Dim statements

Dim something As String = "Hello"
Dim somethingElse As String = "World"
Dim putittogether As String = something & " " & somethingElse

Compiles to:

.method public static void  Main() cil managed
{
  .entrypoint
  .custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) 
  // Code size       28 (0x1c)
  .maxstack  3
  .locals init ([0] string putittogether,
           [1] string something,
           [2] string somethingElse)
  IL_0000:  nop
  IL_0001:  ldstr      "Hello"
  IL_0006:  stloc.1
  IL_0007:  ldstr      "World"
  IL_000c:  stloc.2
  IL_000d:  ldloc.1
  IL_000e:  ldstr      " "
  IL_0013:  ldloc.2
  IL_0014:  call       string [mscorlib]System.String::Concat(string,
                                                              string,
                                                              string)
  IL_0019:  stloc.0
  IL_001a:  nop
  IL_001b:  ret
} // end of method Module1::Main

Second example - all one line

Dim something As String = "Hello",
somethingElse As String = "World",
putittogether As String = something & " " & somethingElse

compiles to:

.method public static void  Main() cil managed
{
  .entrypoint
  .custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) 
  // Code size       28 (0x1c)
  .maxstack  3
  .locals init ([0] string putittogether,
           [1] string something,
           [2] string somethingElse)
  IL_0000:  nop
  IL_0001:  ldstr      "Hello"
  IL_0006:  stloc.1
  IL_0007:  ldstr      "World"
  IL_000c:  stloc.2
  IL_000d:  ldloc.1
  IL_000e:  ldstr      " "
  IL_0013:  ldloc.2
  IL_0014:  call       string [mscorlib]System.String::Concat(string,
                                                              string,
                                                              string)
  IL_0019:  stloc.0
  IL_001a:  nop
  IL_001b:  ret
} // end of method Module1::Main

Upvotes: 1

Related Questions