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. General Programming
  3. Visual Basic
  4. VBer new to VB.net - handles divide by zero?

VBer new to VB.net - handles divide by zero?

Scheduled Pinned Locked Moved Visual Basic
csharphelpquestionvisual-studio
27 Posts 7 Posters 0 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.
  • D Daniel1324

    What percentage of applications you bought and run on your desktop were written in VB ? Good point. I actually prefer C# and I am at least as good in C# as I am in VB. But I'm starting college Monday and part of the course is learning VB.net. I have a love hate relaionship with it... On one hand, I love writing programs in it because, well... its easy. On the other hand, I hate having to tell people that its written Visual Basic.

    C Offline
    C Offline
    Christian Graus
    wrote on last edited by
    #6

    Daniel1324 wrote: Good point. *grin* Daniel1324 wrote: On one hand, I love writing programs in it because, well... its easy. I don't think C# is any harder. In fact, I think it's easier, because of the many traps in VB. Christian Graus - Microsoft MVP - C++

    1 Reply Last reply
    0
    • D DaveC426913

      I am going through the exercises in a textbook to learn about exception handling. This is my code: Dim n1, n2 As Integer Dim n3 As Single n1 = CInt(txtIn1.Text) n2 = CInt(txtIn2.Text) Try lblOut.Text = n1 / n2 Catch ex As Exception lblWarn.Text = "Warning!" End Try 1] The book says Catch e As Exception, but Visual Studio defaults to 'ex' instead of 'e'. If I deliberately put in 'e', I get a build error: "Variable 'e' hides a variable in an enclosing block." What is wrong here? 2] It seems to me that, if a zero is put into txtIn2, it should throw an error. It doesn't. It handles it gracefully, but unexpectedly, putting the text 'Infinity' into lblOut. How am I suppsoed to learn exception handling if it won't act ... exceptional! ________________________________________________________________________ Dave Y10K bug! Let's not get caught with our pants down **AGAIN**! (DC 02002)

      P Offline
      P Offline
      progload
      wrote on last edited by
      #7

      Now that the rest of you are done, trying to thrash VB.Net Here is the reason the lblOut Has Infinity in it. Exception Invalid operation Exception - An operand is invalid for the operation to be performed. Return Value: NaN Division by zero Exception An attempt is made to divide a non-zero value by zero. Returns: Infinity (1/-0 = negative infinity) Overflow Exception The result of an operation is too large to be represented. Returns: Positive or negative infinity. Underflow Exception The result of an operation is too small to be represented. Returns: Positive or negative zero. Inexact Exception The rounded result of an operation is not exact. Returns: The calculated value. cref: IEEE-754/IEC 60559 progload

      D 1 Reply Last reply
      0
      • P progload

        Now that the rest of you are done, trying to thrash VB.Net Here is the reason the lblOut Has Infinity in it. Exception Invalid operation Exception - An operand is invalid for the operation to be performed. Return Value: NaN Division by zero Exception An attempt is made to divide a non-zero value by zero. Returns: Infinity (1/-0 = negative infinity) Overflow Exception The result of an operation is too large to be represented. Returns: Positive or negative infinity. Underflow Exception The result of an operation is too small to be represented. Returns: Positive or negative zero. Inexact Exception The rounded result of an operation is not exact. Returns: The calculated value. cref: IEEE-754/IEC 60559 progload

        D Offline
        D Offline
        DaveC426913
        wrote on last edited by
        #8

        Did I stumble into the wrong forum? No wait, it still says Visual "Basic / VB.NET" across the top. Are there any VB programmers in here? That's sort of what I was, you know, expecting. :mad: So anyways. Progload, if division by zero *is* an exception thrown, why did it not get caught? ________________________________________________________________________ Dave Y10K bug! Let's not get caught with our pants down **AGAIN**! (DC 02002)

        P C 2 Replies Last reply
        0
        • D DaveC426913

          Did I stumble into the wrong forum? No wait, it still says Visual "Basic / VB.NET" across the top. Are there any VB programmers in here? That's sort of what I was, you know, expecting. :mad: So anyways. Progload, if division by zero *is* an exception thrown, why did it not get caught? ________________________________________________________________________ Dave Y10K bug! Let's not get caught with our pants down **AGAIN**! (DC 02002)

          P Offline
          P Offline
          progload
          wrote on last edited by
          #9

          Dave, The Divide-by Function("\") caught the exception, and produced a Text Message = "Infinity" Thus the statement "ex" would be false, No Exception. That is by design... It's no "trick or trap". You can test this by doing this, It will now throw the exception to "ex": Dim n1, n2, n3 as integer Try n3 = n1 \ n2 Catch ex As Exception Label2.Text = "Warning! " & ex.Message End Try Hope this helps dave. Progoad

          D 1 Reply Last reply
          0
          • P progload

            Dave, The Divide-by Function("\") caught the exception, and produced a Text Message = "Infinity" Thus the statement "ex" would be false, No Exception. That is by design... It's no "trick or trap". You can test this by doing this, It will now throw the exception to "ex": Dim n1, n2, n3 as integer Try n3 = n1 \ n2 Catch ex As Exception Label2.Text = "Warning! " & ex.Message End Try Hope this helps dave. Progoad

            D Offline
            D Offline
            DaveC426913
            wrote on last edited by
            #10

            So, the key is making n3 an integer. If it's anything else, it won't throw the exception. It's confusing, but it's really just an example from the book, so no big deal. I should have checked out the book more carefully before purchasing - it's 3 years old. Anyway, now that I'm into it, I'm seeing that this book is covering basic stuff I already know about VB. (The first time I looked at VB.NET code, I was terrified by all the "Region / Friend WithEvents Button1 As System.Windows.Forms.Button" stuff - I thought I was starting at square one.) Once the object-oriented stuff from my little bit of Java programming comes back, I'll be more comfortable. ________________________________________________________________________ Dave Y10K bug! Let's not get caught with our pants down **AGAIN**! (DC 02002)

            P 1 Reply Last reply
            0
            • D DaveC426913

              So, the key is making n3 an integer. If it's anything else, it won't throw the exception. It's confusing, but it's really just an example from the book, so no big deal. I should have checked out the book more carefully before purchasing - it's 3 years old. Anyway, now that I'm into it, I'm seeing that this book is covering basic stuff I already know about VB. (The first time I looked at VB.NET code, I was terrified by all the "Region / Friend WithEvents Button1 As System.Windows.Forms.Button" stuff - I thought I was starting at square one.) Once the object-oriented stuff from my little bit of Java programming comes back, I'll be more comfortable. ________________________________________________________________________ Dave Y10K bug! Let's not get caught with our pants down **AGAIN**! (DC 02002)

              P Offline
              P Offline
              progload
              wrote on last edited by
              #11

              Yes, The label control is a text control, thus if you return the text ("Infinity") into it, why would it throw an exeception (to ex) because it is text? The author was not following proper basic syntax coding... and created his own "bug". By the Way, I realy enjoy VB and VB.Net, and it's Math capability. Beyond what you see a lot of folks saying... I think it is a very powerfull language. Have fun learning it.. I am.. progload

              D 1 Reply Last reply
              0
              • P progload

                Yes, The label control is a text control, thus if you return the text ("Infinity") into it, why would it throw an exeception (to ex) because it is text? The author was not following proper basic syntax coding... and created his own "bug". By the Way, I realy enjoy VB and VB.Net, and it's Math capability. Beyond what you see a lot of folks saying... I think it is a very powerfull language. Have fun learning it.. I am.. progload

                D Offline
                D Offline
                DaveC426913
                wrote on last edited by
                #12

                progload wrote: thus if you return the text ("Infinity") into it Ah, well I'd assumed it would be the / operation that would throw it. I see what you're saying now. The / operation catches the error internally and simply returns 'infinity'. Thus, externally, it is not an error at all until I attempt to do something with it. In fact, the error it's been coded to throw isn't arithmetical at all, it is a type error - I can't assume that the / operation will return a numerical value; it could return a string. Small potatoes. This is actually baby steps towards developing an app that will access the Windows Media Services 9 SDK to manipulate broadcast media publishing points. And even THAT is an intermediate step to transposing it to ASP.NET so I can do it from a web app. Can you say 'out of my league'? Why do I do this to myself? ________________________________________________________________________ Dave Y10K bug! Let's not get caught with our pants down **AGAIN**! (DC 02002)

                1 Reply Last reply
                0
                • C Christian Graus

                  DaveC426913 wrote: n1 = CInt(txtIn1.Text) n2 = CInt(txtIn2.Text) I don't think you're supposed to use CInt, you should use Convert.ToInt32. VB.NET contains a lot of VB6 crap, because the VB community complained when Microsoft initially ( and with good reason ) removed it. DaveC426913 wrote: The book says Catch e As Exception, but Visual Studio defaults to 'ex' instead of 'e'. If I deliberately put in 'e', I get a build error: "Variable 'e' hides a variable in an enclosing block." What is wrong here? 1/ it doesn't matter what you call your variable 2/ you have another variable called e that's visible to this one, so you can't do this, because one overrides the other 3/ you should catch DivideByZeroException, not just Exception. This will catch ANY error, including ones you have not anticipated and/or can't recover from. DaveC426913 wrote: 2] It seems to me that, if a zero is put into txtIn2, it should throw an error. It doesn't. It handles it gracefully, but unexpectedly, putting the text 'Infinity' into lblOut. Good question. VB sucks. Use C#. I tried this now, and even if I set n3 to be n1/n2, it still does the same. C# throws an exception, like all real programming languages. I find it hilarious that your book doesn't know that this doesn't throw an exception, I wonder if the author bothered to try it. *edit* I apologise if the above seemed harsh, but I have to tell you, the whole office is laughing about this VB 'feature' right now. I'm not wanting to give you a hard time, just VB. Christian Graus - Microsoft MVP - C++

                  D Offline
                  D Offline
                  Dave Kreskowiak
                  wrote on last edited by
                  #13

                  Christian Graus wrote: I don't think you're supposed to use CInt, you should use Convert.ToInt32. Actually, you can still use CInt without any worries of it being on the chopping block in 2005. CInt is actually faster than using Convert.ToInt32 because CInt's conversion code is compiled in-line with the expression. There's no method call to setup and jump to. His code is converting the DivideByZero exception to a string before it blows up. This results in the string "Infinity" being returned. RageInTheMachine9532 "...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome

                  C 1 Reply Last reply
                  0
                  • D DaveC426913

                    I am going through the exercises in a textbook to learn about exception handling. This is my code: Dim n1, n2 As Integer Dim n3 As Single n1 = CInt(txtIn1.Text) n2 = CInt(txtIn2.Text) Try lblOut.Text = n1 / n2 Catch ex As Exception lblWarn.Text = "Warning!" End Try 1] The book says Catch e As Exception, but Visual Studio defaults to 'ex' instead of 'e'. If I deliberately put in 'e', I get a build error: "Variable 'e' hides a variable in an enclosing block." What is wrong here? 2] It seems to me that, if a zero is put into txtIn2, it should throw an error. It doesn't. It handles it gracefully, but unexpectedly, putting the text 'Infinity' into lblOut. How am I suppsoed to learn exception handling if it won't act ... exceptional! ________________________________________________________________________ Dave Y10K bug! Let's not get caught with our pants down **AGAIN**! (DC 02002)

                    T Offline
                    T Offline
                    Thomas Stockwell
                    wrote on last edited by
                    #14

                    1] The book says Catch e As Exception, but Visual Studio defaults to 'ex' instead of 'e'. If I deliberately put in 'e', I get a build error: "Variable 'e' hides a variable in an enclosing block." What is wrong here? The book that you are using may have a different definition in its parameters for your code block. For example: public sub Test(byval sender as object, byval e as system.eventargs) Dim n1, n2 As Integer Dim n3 As Single n1 = CInt(txtIn1.Text) n2 = CInt(txtIn2.Text) Try lblOut.Text = n1 / n2 Catch e As Exception lblWarn.Text = "Warning!" End Try end sub If you tried to catch 'e as an exception' than the e would override the 'e as system.eventargs' which is in the sub parameter. So you can change either of the two variables but they cannot be the same. Look in your book and see if the parameters for the sub or function use an e variable.

                    R 1 Reply Last reply
                    0
                    • T Thomas Stockwell

                      1] The book says Catch e As Exception, but Visual Studio defaults to 'ex' instead of 'e'. If I deliberately put in 'e', I get a build error: "Variable 'e' hides a variable in an enclosing block." What is wrong here? The book that you are using may have a different definition in its parameters for your code block. For example: public sub Test(byval sender as object, byval e as system.eventargs) Dim n1, n2 As Integer Dim n3 As Single n1 = CInt(txtIn1.Text) n2 = CInt(txtIn2.Text) Try lblOut.Text = n1 / n2 Catch e As Exception lblWarn.Text = "Warning!" End Try end sub If you tried to catch 'e as an exception' than the e would override the 'e as system.eventargs' which is in the sub parameter. So you can change either of the two variables but they cannot be the same. Look in your book and see if the parameters for the sub or function use an e variable.

                      R Offline
                      R Offline
                      rwestgraham
                      wrote on last edited by
                      #15

                      In addition to the comment above, I would advide just assuming "ex" as a standard way for naming exceptions, because for all practical purposes you should just consider "e" as a system reserved variable because NET always declares event arguments as "e". As far as the "VB is crap" comments, you'll get use to that. It happens on a regular basis. This is a tired, no longer relevant pet argument that some tired, no longer relevant people seem to be unable to let go of. The reality is that although there are some very minor differences between C# and VB.NET, once you learn to program against the NET framework, you will discover that there is essentially no practical difference. They both compile to exactly the same machine level code, and they both have for all practical purposes the same level of functionality. Just tune it out.

                      1 Reply Last reply
                      0
                      • D Dave Kreskowiak

                        Christian Graus wrote: I don't think you're supposed to use CInt, you should use Convert.ToInt32. Actually, you can still use CInt without any worries of it being on the chopping block in 2005. CInt is actually faster than using Convert.ToInt32 because CInt's conversion code is compiled in-line with the expression. There's no method call to setup and jump to. His code is converting the DivideByZero exception to a string before it blows up. This results in the string "Infinity" being returned. RageInTheMachine9532 "...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome

                        C Offline
                        C Offline
                        Christian Graus
                        wrote on last edited by
                        #16

                        Isn't CInt one of the legacy methods that was going to be removed ? I wasn't sure on this. Dave Kreskowiak wrote: His code is converting the DivideByZero exception to a string before it blows up. This results in the string "Infinity" being returned. Wrong. I converted into code which didn't use strings at all, and the Single variable gets the VALUE of positive Infinity. That's where the string value comes from, the Single, which does not blow up. Then I changed the code to set to an int, and it DOES blow up then, but it doesn't throw a DivideByZero exception, it throws an OverflowException. C# will blow up on a divide by zero, no matter what type it's being set to, and it throws the right exception. Do you have an explanation for this that doesn't involve the VB.NET design team spending most of their time drunk ? Because we spent a Friday laughing about it here ( where we never use VB.NET ). Christian Graus - Microsoft MVP - C++

                        D P 2 Replies Last reply
                        0
                        • C Christian Graus

                          Isn't CInt one of the legacy methods that was going to be removed ? I wasn't sure on this. Dave Kreskowiak wrote: His code is converting the DivideByZero exception to a string before it blows up. This results in the string "Infinity" being returned. Wrong. I converted into code which didn't use strings at all, and the Single variable gets the VALUE of positive Infinity. That's where the string value comes from, the Single, which does not blow up. Then I changed the code to set to an int, and it DOES blow up then, but it doesn't throw a DivideByZero exception, it throws an OverflowException. C# will blow up on a divide by zero, no matter what type it's being set to, and it throws the right exception. Do you have an explanation for this that doesn't involve the VB.NET design team spending most of their time drunk ? Because we spent a Friday laughing about it here ( where we never use VB.NET ). Christian Graus - Microsoft MVP - C++

                          D Offline
                          D Offline
                          Dave Kreskowiak
                          wrote on last edited by
                          #17

                          Christian Graus wrote: Wrong. I converted into code which didn't use strings at all, and the Single variable gets the VALUE of positive Infinity. That's where the string value comes from, the Single, which does not blow up. Sorry. I suffered a momentary rectal/cranial inversion. ;P It would be interesting to see what IL is generated for the same code. I'll try and take a look at that when I get to work. RageInTheMachine9532 "...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome

                          C 1 Reply Last reply
                          0
                          • D Dave Kreskowiak

                            Christian Graus wrote: Wrong. I converted into code which didn't use strings at all, and the Single variable gets the VALUE of positive Infinity. That's where the string value comes from, the Single, which does not blow up. Sorry. I suffered a momentary rectal/cranial inversion. ;P It would be interesting to see what IL is generated for the same code. I'll try and take a look at that when I get to work. RageInTheMachine9532 "...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome

                            C Offline
                            C Offline
                            Christian Graus
                            wrote on last edited by
                            #18

                            Dave Kreskowiak wrote: I suffered a momentary rectal/cranial inversion *grin* I'd certainly forgive you for assuming this would not be the case, it's pretty screwed up. Dave Kreskowiak wrote: It would be interesting to see what IL is generated for the same code. I'll try and take a look at that when I get to work. I'd be really interested to hear your thoughts. Overall, I thought that VB.NET and C# did roughly the same thing, and this sort of difference is frankly astounding to me. Christian Graus - Microsoft MVP - C++

                            D 1 Reply Last reply
                            0
                            • C Christian Graus

                              Isn't CInt one of the legacy methods that was going to be removed ? I wasn't sure on this. Dave Kreskowiak wrote: His code is converting the DivideByZero exception to a string before it blows up. This results in the string "Infinity" being returned. Wrong. I converted into code which didn't use strings at all, and the Single variable gets the VALUE of positive Infinity. That's where the string value comes from, the Single, which does not blow up. Then I changed the code to set to an int, and it DOES blow up then, but it doesn't throw a DivideByZero exception, it throws an OverflowException. C# will blow up on a divide by zero, no matter what type it's being set to, and it throws the right exception. Do you have an explanation for this that doesn't involve the VB.NET design team spending most of their time drunk ? Because we spent a Friday laughing about it here ( where we never use VB.NET ). Christian Graus - Microsoft MVP - C++

                              P Offline
                              P Offline
                              progload
                              wrote on last edited by
                              #19

                              Christian, If you realy would like to know why.. it throws an OverflowException as you said.. Take a look here: http://support.microsoft.com/default.aspx?scid=kb;en-us;Q315965&ID=kb;en-us;Q315965&SD=MSDN[^] And Here: http://visualbasic.about.com/od/usingvbnet/l/bldyknaninfa.htm[^] I think it should clear it up for you. progload

                              C 1 Reply Last reply
                              0
                              • P progload

                                Christian, If you realy would like to know why.. it throws an OverflowException as you said.. Take a look here: http://support.microsoft.com/default.aspx?scid=kb;en-us;Q315965&ID=kb;en-us;Q315965&SD=MSDN[^] And Here: http://visualbasic.about.com/od/usingvbnet/l/bldyknaninfa.htm[^] I think it should clear it up for you. progload

                                C Offline
                                C Offline
                                Christian Graus
                                wrote on last edited by
                                #20

                                Thanks for the links. Mathematically, you CAN divide by zero, but what you get is "infinity". Actually, this is not true. Google some maths sites if you don't believe me. Either way, as the article states, this leaves the way open for some serious problems in business apps that don't work hard to avoid this happening. I don't understand the integer divide ( \ ) thing. Does that stop VB from implicitly converting ints to floats ? I guess C#, being more strongly typed, wouldn't need that, and that would go *some* way to explaining why C# and VB.NET behave so differently from one another in this instance. Thanks for the info. Christian Graus - Microsoft MVP - C++

                                P 1 Reply Last reply
                                0
                                • D DaveC426913

                                  Did I stumble into the wrong forum? No wait, it still says Visual "Basic / VB.NET" across the top. Are there any VB programmers in here? That's sort of what I was, you know, expecting. :mad: So anyways. Progload, if division by zero *is* an exception thrown, why did it not get caught? ________________________________________________________________________ Dave Y10K bug! Let's not get caught with our pants down **AGAIN**! (DC 02002)

                                  C Offline
                                  C Offline
                                  Christian Graus
                                  wrote on last edited by
                                  #21

                                  Sorry Dave, you seem to have stumbled upon an amazingly illogical and inconsistent piece of VB.NET behaviour, hence the discussion. I thought I did in fact explain how to get the exception to throw though, didn't I ? Christian Graus - Microsoft MVP - C++

                                  1 Reply Last reply
                                  0
                                  • C Christian Graus

                                    Thanks for the links. Mathematically, you CAN divide by zero, but what you get is "infinity". Actually, this is not true. Google some maths sites if you don't believe me. Either way, as the article states, this leaves the way open for some serious problems in business apps that don't work hard to avoid this happening. I don't understand the integer divide ( \ ) thing. Does that stop VB from implicitly converting ints to floats ? I guess C#, being more strongly typed, wouldn't need that, and that would go *some* way to explaining why C# and VB.NET behave so differently from one another in this instance. Thanks for the info. Christian Graus - Microsoft MVP - C++

                                    P Offline
                                    P Offline
                                    progload
                                    wrote on last edited by
                                    #22

                                    Christian, Integer Division under VB.Net Operators: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbls7/html/vblrfvbspec11_5_4.asp[^] and a simple comparison: http://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.html[^] Hope this helps. progload

                                    C 1 Reply Last reply
                                    0
                                    • C Christian Graus

                                      Dave Kreskowiak wrote: I suffered a momentary rectal/cranial inversion *grin* I'd certainly forgive you for assuming this would not be the case, it's pretty screwed up. Dave Kreskowiak wrote: It would be interesting to see what IL is generated for the same code. I'll try and take a look at that when I get to work. I'd be really interested to hear your thoughts. Overall, I thought that VB.NET and C# did roughly the same thing, and this sort of difference is frankly astounding to me. Christian Graus - Microsoft MVP - C++

                                      D Offline
                                      D Offline
                                      Dave Kreskowiak
                                      wrote on last edited by
                                      #23

                                      After doing a little code and IL research and going back to the VB.NET docs on mathematical operators, all has become crystal clear. There are TWO division operators in VB.NET. Click here[^] for the docs, or just read on... The normal one, that we're all used to using in any language, is "/". Well, in VB.NET, this operator is only used to divide two floating point numbers. The operator is defined for both the Single and Double types and also the Decimal type. The Single and Double types are evaluated using standard IEEE 754 rules. Nothing new here, it's what we've been using for decades in C/C++ on floating point values and where our "interpretation" problem comes in while evaluating the original posters n1/n2 expression. The Decimal type is a little different. If the right-hand operand is 0, the a System.DivideByZeroException is thrown. If the resulting value is too large to hold in the Decimal type a System.Overflow exception is thrown. If the resulting value is too small, then the Decimal type result will be 0. The second division operator in VB.NET is "\" and is reserved for integer division using the VB.NET Byte, Short, Integer, and Long types. This is the division that the equivilent C# code is doing when comparing VISUALLY identical VB.NET and C# code using integer operands! Now, according to MSDN: "According to normal operator resolution rules, regular division purely between operands of types such as Byte, Short, Integer, and Long would cause both operands to be converted to type Decimal. However, when doing operator resolution on the division operator when neither type is Decimal, Double is considered narrower than Decimal. This convention is followed because Double division is more efficient than Decimal division." Keeping that statement in mind, here's the proof of what's going on with the OP's code: This is the test function code for VB.NET:

                                      Dim n1, n2 As Integer
                                      n1 = Convert.ToInt32("32")
                                      n2 = Convert.ToInt32("0")
                                      Console.WriteLine(n1 / n2)

                                      The output is the string "Infinity". Something C# and C/C++ coders wouldn't expect to see. The test function in C# is:

                                      int n1;
                                      int n2;
                                      n1 = Convert.ToInt32(@"32");
                                      n2 = Convert.ToInt32(@"0");
                                      Con

                                      C 1 Reply Last reply
                                      0
                                      • P progload

                                        Christian, Integer Division under VB.Net Operators: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbls7/html/vblrfvbspec11_5_4.asp[^] and a simple comparison: http://www.harding.edu/USER/fmccown/WWW/vbnet_csharp_comparison.html[^] Hope this helps. progload

                                        C Offline
                                        C Offline
                                        Christian Graus
                                        wrote on last edited by
                                        #24

                                        Thanks :-) Christian Graus - Microsoft MVP - C++

                                        1 Reply Last reply
                                        0
                                        • D Dave Kreskowiak

                                          After doing a little code and IL research and going back to the VB.NET docs on mathematical operators, all has become crystal clear. There are TWO division operators in VB.NET. Click here[^] for the docs, or just read on... The normal one, that we're all used to using in any language, is "/". Well, in VB.NET, this operator is only used to divide two floating point numbers. The operator is defined for both the Single and Double types and also the Decimal type. The Single and Double types are evaluated using standard IEEE 754 rules. Nothing new here, it's what we've been using for decades in C/C++ on floating point values and where our "interpretation" problem comes in while evaluating the original posters n1/n2 expression. The Decimal type is a little different. If the right-hand operand is 0, the a System.DivideByZeroException is thrown. If the resulting value is too large to hold in the Decimal type a System.Overflow exception is thrown. If the resulting value is too small, then the Decimal type result will be 0. The second division operator in VB.NET is "\" and is reserved for integer division using the VB.NET Byte, Short, Integer, and Long types. This is the division that the equivilent C# code is doing when comparing VISUALLY identical VB.NET and C# code using integer operands! Now, according to MSDN: "According to normal operator resolution rules, regular division purely between operands of types such as Byte, Short, Integer, and Long would cause both operands to be converted to type Decimal. However, when doing operator resolution on the division operator when neither type is Decimal, Double is considered narrower than Decimal. This convention is followed because Double division is more efficient than Decimal division." Keeping that statement in mind, here's the proof of what's going on with the OP's code: This is the test function code for VB.NET:

                                          Dim n1, n2 As Integer
                                          n1 = Convert.ToInt32("32")
                                          n2 = Convert.ToInt32("0")
                                          Console.WriteLine(n1 / n2)

                                          The output is the string "Infinity". Something C# and C/C++ coders wouldn't expect to see. The test function in C# is:

                                          int n1;
                                          int n2;
                                          n1 = Convert.ToInt32(@"32");
                                          n2 = Convert.ToInt32(@"0");
                                          Con

                                          C Offline
                                          C Offline
                                          Christian Graus
                                          wrote on last edited by
                                          #25

                                          Thanks - I had pieced part of this together with some help already ( the two operators thing ), but this makes everything quite clear. The core issue then is the convert to a float64. I wonder if these conversions behind the scenes are a reason for the argument that VB.NET is slower than C# ? Does this mean that C# can't divide using IEEE 754 rules ? Or is it just that VB.NET, being loosely typed, does conversions behind the scenes that C# does not. Certainly I could see where the overflow exception came from, that all makes sense now. Christian Graus - Microsoft MVP - C++

                                          D 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