Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Other Discussions
  3. Clever Code
  4. VB.Net's Dim [modified]

VB.Net's Dim [modified]

Scheduled Pinned Locked Moved Clever Code
csharpphpvisual-studiocom
20 Posts 15 Posters 4 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Offline
    K Offline
    KramII
    wrote on last edited by
    #1

    ...but you already knew that ;P Anyway, someone I know recently wrote an app that did something like this (in real life, the code was much more complex, but this is the essence): Sub Main() For i As Integer = 1 To 5 Dim b As Boolean Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub He intended the result to be:

    False
    False
    False
    False
    False

    Which is reasonable, given that MSDN[^] says "If you do not specify initializer for a variable, Visual Basic initializes it to the default value for its data type", and the default for Boolean is False. Instead he actually got:

    False
    True
    True
    True
    True

    (Try it if you don't believe me!) The solution was to explicitly assign the value of 'b': Sub Main() For i As Integer = 1 To 5 Dim b As Boolean **= False** Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub Result:

    False
    False
    False
    False
    False

    Edit: Corrected the error in the final example, as pointed out by leppie.

    KramII

    modified on Wednesday, September 10, 2008 5:13 AM

    L C V I 4 Replies Last reply
    0
    • K KramII

      ...but you already knew that ;P Anyway, someone I know recently wrote an app that did something like this (in real life, the code was much more complex, but this is the essence): Sub Main() For i As Integer = 1 To 5 Dim b As Boolean Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub He intended the result to be:

      False
      False
      False
      False
      False

      Which is reasonable, given that MSDN[^] says "If you do not specify initializer for a variable, Visual Basic initializes it to the default value for its data type", and the default for Boolean is False. Instead he actually got:

      False
      True
      True
      True
      True

      (Try it if you don't believe me!) The solution was to explicitly assign the value of 'b': Sub Main() For i As Integer = 1 To 5 Dim b As Boolean **= False** Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub Result:

      False
      False
      False
      False
      False

      Edit: Corrected the error in the final example, as pointed out by leppie.

      KramII

      modified on Wednesday, September 10, 2008 5:13 AM

      L Offline
      L Offline
      leppie
      wrote on last edited by
      #2

      Ok something I do not get. The 1st result shows 5 entries, the 2nd 5, and the third 4. Something fishy... (besides the described behavior)

      xacc.ide - now with TabsToSpaces support
      IronScheme - 1.0 alpha 4a out now (29 May 2008)

      B K 2 Replies Last reply
      0
      • L leppie

        Ok something I do not get. The 1st result shows 5 entries, the 2nd 5, and the third 4. Something fishy... (besides the described behavior)

        xacc.ide - now with TabsToSpaces support
        IronScheme - 1.0 alpha 4a out now (29 May 2008)

        B Offline
        B Offline
        Baconbutty
        wrote on last edited by
        #3

        It probably got so confused about what value it should have that it just gave up.

        I still remember having to write your own code in FORTRAN rather than be a cut and paste merchant being pampered by colour coded Intellisense - ahh proper programming - those were the days :)

        1 Reply Last reply
        0
        • K KramII

          ...but you already knew that ;P Anyway, someone I know recently wrote an app that did something like this (in real life, the code was much more complex, but this is the essence): Sub Main() For i As Integer = 1 To 5 Dim b As Boolean Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub He intended the result to be:

          False
          False
          False
          False
          False

          Which is reasonable, given that MSDN[^] says "If you do not specify initializer for a variable, Visual Basic initializes it to the default value for its data type", and the default for Boolean is False. Instead he actually got:

          False
          True
          True
          True
          True

          (Try it if you don't believe me!) The solution was to explicitly assign the value of 'b': Sub Main() For i As Integer = 1 To 5 Dim b As Boolean **= False** Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub Result:

          False
          False
          False
          False
          False

          Edit: Corrected the error in the final example, as pointed out by leppie.

          KramII

          modified on Wednesday, September 10, 2008 5:13 AM

          C Offline
          C Offline
          Chris Meech
          wrote on last edited by
          #4

          When there is no initialization, the memory for the boolean is being re-used without any changes to it. Hence the true value. Probably another case of the documentation not being completely true. Or false. ;)

          Chris Meech I am Canadian. [heard in a local bar] In theory there is no difference between theory and practice. In practice there is. [Yogi Berra]

          K P 2 Replies Last reply
          0
          • L leppie

            Ok something I do not get. The 1st result shows 5 entries, the 2nd 5, and the third 4. Something fishy... (besides the described behavior)

            xacc.ide - now with TabsToSpaces support
            IronScheme - 1.0 alpha 4a out now (29 May 2008)

            K Offline
            K Offline
            KramII
            wrote on last edited by
            #5

            My mistake. Good spot, leppie. It should be 5 entries for each example.

            KramII

            1 Reply Last reply
            0
            • C Chris Meech

              When there is no initialization, the memory for the boolean is being re-used without any changes to it. Hence the true value. Probably another case of the documentation not being completely true. Or false. ;)

              Chris Meech I am Canadian. [heard in a local bar] In theory there is no difference between theory and practice. In practice there is. [Yogi Berra]

              K Offline
              K Offline
              KramII
              wrote on last edited by
              #6

              Chris Meech wrote:

              Probably another case of the documentation not being completely true. Or false.

              :laugh: Curiously, MSDN also states (under Troubleshooting), "The Dim statement is not itself an executable statement". Whatever that means.

              KramII

              C R S L B 5 Replies Last reply
              0
              • K KramII

                Chris Meech wrote:

                Probably another case of the documentation not being completely true. Or false.

                :laugh: Curiously, MSDN also states (under Troubleshooting), "The Dim statement is not itself an executable statement". Whatever that means.

                KramII

                C Offline
                C Offline
                CARPETBURNER
                wrote on last edited by
                #7

                its always best practice to initialise a variable before you use it. VB's IDE warns you of this, Any good programmer should be doing this out of habit.

                K R 2 Replies Last reply
                0
                • K KramII

                  Chris Meech wrote:

                  Probably another case of the documentation not being completely true. Or false.

                  :laugh: Curiously, MSDN also states (under Troubleshooting), "The Dim statement is not itself an executable statement". Whatever that means.

                  KramII

                  R Offline
                  R Offline
                  Robert Royall
                  wrote on last edited by
                  #8

                  I think that means you can't set a breakpoint on a line with just a dim statement. At least, that's the way it's always been in VB before.

                  Imagine that you are hired to build a bridge over a river which gets slightly wider every day; sometimes it shrinks but nobody can predict when. Your client provides no concrete or steel, only timber and cut stone (but they won't tell you what kind). The coefficient of gravity changes randomly from hour to hour, as does the viscosity of air. Your only tools are a hacksaw, a chainsaw, a rubber mallet, and a length of rope. Welcome to my world. -Me explaining my job to an engineer

                  1 Reply Last reply
                  0
                  • C CARPETBURNER

                    its always best practice to initialise a variable before you use it. VB's IDE warns you of this, Any good programmer should be doing this out of habit.

                    K Offline
                    K Offline
                    KramII
                    wrote on last edited by
                    #9

                    I quite agree, and have advised my colleague to do so in future. Nevertheless, I was surprised by results of missing out the initialization in this case. IMHO, VB.Net should insist on initialization. Ideally, the compiler would refuse to compile without explicit initialization. Alternatively (to stop legacy code breaking) the IDE could automatically insert the initialization for you, even if the compiler could live without it. Incidentally, there here are a couple of links to related material: Gain performance by not initializing variables[^] VB.NET and variable initialization [^]

                    KramII

                    D 1 Reply Last reply
                    0
                    • K KramII

                      I quite agree, and have advised my colleague to do so in future. Nevertheless, I was surprised by results of missing out the initialization in this case. IMHO, VB.Net should insist on initialization. Ideally, the compiler would refuse to compile without explicit initialization. Alternatively (to stop legacy code breaking) the IDE could automatically insert the initialization for you, even if the compiler could live without it. Incidentally, there here are a couple of links to related material: Gain performance by not initializing variables[^] VB.NET and variable initialization [^]

                      KramII

                      D Offline
                      D Offline
                      Dan Neely
                      wrote on last edited by
                      #10

                      KramII wrote:

                      Gain performance by not initializing variables[^]

                      Only in .net 1.1. in 2005, explicit constructor initialization is faster. http://www.codeproject.com/script/Forums/View.aspx?fid=182387&msg=1115892[^]

                      Today's lesson is brought to you by the word "niggardly". Remember kids, don't attribute to racism what can be explained by Scandinavian language roots. -- Robert Royall

                      K 1 Reply Last reply
                      0
                      • D Dan Neely

                        KramII wrote:

                        Gain performance by not initializing variables[^]

                        Only in .net 1.1. in 2005, explicit constructor initialization is faster. http://www.codeproject.com/script/Forums/View.aspx?fid=182387&msg=1115892[^]

                        Today's lesson is brought to you by the word "niggardly". Remember kids, don't attribute to racism what can be explained by Scandinavian language roots. -- Robert Royall

                        K Offline
                        K Offline
                        KramII
                        wrote on last edited by
                        #11

                        That's good to know, thanks.

                        KramII

                        1 Reply Last reply
                        0
                        • K KramII

                          Chris Meech wrote:

                          Probably another case of the documentation not being completely true. Or false.

                          :laugh: Curiously, MSDN also states (under Troubleshooting), "The Dim statement is not itself an executable statement". Whatever that means.

                          KramII

                          S Offline
                          S Offline
                          Scott Barbour
                          wrote on last edited by
                          #12

                          What that means is that the Dim statement does not behave like a normal statement. The placement defines the scope of the variable within the procedure, but it is never "executed" as a statement. If you step through the code, you will see that the Dim statement is never executed. FWIW, this behavior occurs in VB6 as well.

                          Sub Main()
                          Dim i As Integer
                          For i = 1 To 5
                          Dim b As Boolean
                          Debug.Print b
                          b = True
                          Next
                          End Sub

                          1 Reply Last reply
                          0
                          • C Chris Meech

                            When there is no initialization, the memory for the boolean is being re-used without any changes to it. Hence the true value. Probably another case of the documentation not being completely true. Or false. ;)

                            Chris Meech I am Canadian. [heard in a local bar] In theory there is no difference between theory and practice. In practice there is. [Yogi Berra]

                            P Offline
                            P Offline
                            peterchen
                            wrote on last edited by
                            #13

                            I guess the default value for POD's - as in C - is "unspecified".

                            Burning Chrome ^ | Linkify!| FoldWithUs! | sighist

                            1 Reply Last reply
                            0
                            • K KramII

                              ...but you already knew that ;P Anyway, someone I know recently wrote an app that did something like this (in real life, the code was much more complex, but this is the essence): Sub Main() For i As Integer = 1 To 5 Dim b As Boolean Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub He intended the result to be:

                              False
                              False
                              False
                              False
                              False

                              Which is reasonable, given that MSDN[^] says "If you do not specify initializer for a variable, Visual Basic initializes it to the default value for its data type", and the default for Boolean is False. Instead he actually got:

                              False
                              True
                              True
                              True
                              True

                              (Try it if you don't believe me!) The solution was to explicitly assign the value of 'b': Sub Main() For i As Integer = 1 To 5 Dim b As Boolean **= False** Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub Result:

                              False
                              False
                              False
                              False
                              False

                              Edit: Corrected the error in the final example, as pointed out by leppie.

                              KramII

                              modified on Wednesday, September 10, 2008 5:13 AM

                              V Offline
                              V Offline
                              V 0
                              wrote on last edited by
                              #14

                              Shows you shouldn't rely on the compiler to assign 'default' values. I always assign "a value" to my variables... :-D

                              V.
                              Stop smoking so you can: Enjoy longer the money you save. Moviereview Archive

                              P 1 Reply Last reply
                              0
                              • V V 0

                                Shows you shouldn't rely on the compiler to assign 'default' values. I always assign "a value" to my variables... :-D

                                V.
                                Stop smoking so you can: Enjoy longer the money you save. Moviereview Archive

                                P Offline
                                P Offline
                                Paul Conrad
                                wrote on last edited by
                                #15

                                V. wrote:

                                I always assign "a value" to my variables...

                                Same here. Easier to just to assign a value and saves from having to track down strange results due to compiler defaults being assigned.

                                "The clue train passed his station without stopping." - John Simmons / outlaw programmer "Real programmers just throw a bunch of 1s and 0s at the computer to see what sticks" - Pete O'Hanlon "Not only do you continue to babble nonsense, you can't even correctly remember the nonsense you babbled just minutes ago." - Rob Graham

                                1 Reply Last reply
                                0
                                • K KramII

                                  Chris Meech wrote:

                                  Probably another case of the documentation not being completely true. Or false.

                                  :laugh: Curiously, MSDN also states (under Troubleshooting), "The Dim statement is not itself an executable statement". Whatever that means.

                                  KramII

                                  L Offline
                                  L Offline
                                  Lost User
                                  wrote on last edited by
                                  #16

                                  It simply means you can't set a breakpoint there. It is not translated to any code and in the disassembly you will not find anything corresponding to that line. Initializing the variable does produce code and therefore you can then see it in the disassembly or place a breakpoint there.

                                  A while ago he asked me what he should have printed on my business cards. I said 'Wizard'. I read books which nobody else understand. Then I do something which nobody understands. After that the computer does something which nobody understands. When asked, I say things about the results which nobody understand. But everybody expects miracles from me on a regular basis. Looks to me like the classical definition of a wizard.

                                  K 1 Reply Last reply
                                  0
                                  • L Lost User

                                    It simply means you can't set a breakpoint there. It is not translated to any code and in the disassembly you will not find anything corresponding to that line. Initializing the variable does produce code and therefore you can then see it in the disassembly or place a breakpoint there.

                                    A while ago he asked me what he should have printed on my business cards. I said 'Wizard'. I read books which nobody else understand. Then I do something which nobody understands. After that the computer does something which nobody understands. When asked, I say things about the results which nobody understand. But everybody expects miracles from me on a regular basis. Looks to me like the classical definition of a wizard.

                                    K Offline
                                    K Offline
                                    KramII
                                    wrote on last edited by
                                    #17

                                    Thanks for explaining. It would be helpful if the document actually said that...

                                    KramII

                                    1 Reply Last reply
                                    0
                                    • K KramII

                                      Chris Meech wrote:

                                      Probably another case of the documentation not being completely true. Or false.

                                      :laugh: Curiously, MSDN also states (under Troubleshooting), "The Dim statement is not itself an executable statement". Whatever that means.

                                      KramII

                                      B Offline
                                      B Offline
                                      BillW33
                                      wrote on last edited by
                                      #18

                                      The Dim statement causes the variable to be initialized upon creation. However, creation occurs only once. The Dim statement is not executed again on each iteration through the loop therefore it does not reinitialize the variable on each iteration. Bill W

                                      1 Reply Last reply
                                      0
                                      • K KramII

                                        ...but you already knew that ;P Anyway, someone I know recently wrote an app that did something like this (in real life, the code was much more complex, but this is the essence): Sub Main() For i As Integer = 1 To 5 Dim b As Boolean Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub He intended the result to be:

                                        False
                                        False
                                        False
                                        False
                                        False

                                        Which is reasonable, given that MSDN[^] says "If you do not specify initializer for a variable, Visual Basic initializes it to the default value for its data type", and the default for Boolean is False. Instead he actually got:

                                        False
                                        True
                                        True
                                        True
                                        True

                                        (Try it if you don't believe me!) The solution was to explicitly assign the value of 'b': Sub Main() For i As Integer = 1 To 5 Dim b As Boolean **= False** Console.WriteLine(b.ToString) b = True Next Console.ReadLine() End Sub Result:

                                        False
                                        False
                                        False
                                        False
                                        False

                                        Edit: Corrected the error in the final example, as pointed out by leppie.

                                        KramII

                                        modified on Wednesday, September 10, 2008 5:13 AM

                                        I Offline
                                        I Offline
                                        Izzet Kerem Kusmezer
                                        wrote on last edited by
                                        #19

                                        The following is also buggy. Imports System public class Test Public Shared Sub Main() For i As Integer = 1 To 5 Dim b As String if i > 1 then Console.WriteLine(b.SubString(2)) end if Console.WriteLine(b) b = "killer" Next Console.ReadLine() End Sub end class Which normally should cause an null reference exception causes ller to be written out, you can't write the same code in C#, because using an uninitialized variable is an error instead of an warning.

                                        1 Reply Last reply
                                        0
                                        • C CARPETBURNER

                                          its always best practice to initialise a variable before you use it. VB's IDE warns you of this, Any good programmer should be doing this out of habit.

                                          R Offline
                                          R Offline
                                          Ray Cassick
                                          wrote on last edited by
                                          #20

                                          I agree, and I do that on a regular basis but in fact the older version so FxCop (not sure if the new version do this0 tell you that doing that is wasted because the framework takes care of the initialization for you. I had just disable that rule in FxCop but I found it interesting that their tool was telling us to do exactly what decades of CS training and classes have beat into our heads as gospel.


                                          FFRF[^]
                                          My LinkedIn profile[^]
                                          My Programmers Blog[^]

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups