0

I have a simple arithmetic to perform in VB.Net, which is as follows;

I've got m_Variable5 of type String = "325" which is passed from another object. The operations are;

m_Variable5 = Convert.ToString(Convert.ToInt32(m_Variable4, InvariantCulture) / 7, InvariantCulture)
m_Variable5 = Convert.ToString(Convert.ToInt32(m_Variable5, InvariantCulture) + 1, InvariantCulture)
m_Variable5 = Convert.ToString(Convert.ToInt32(m_Variable5, InvariantCulture) * 7, InvariantCulture)

On doing these 3 operations, I got a type error on the second one. Error message says "Input string was not in a correct format."

but the same operations when done using VB conversion functions, works properly;

 m_Variable5 = CStr(CInt(m_Variable4) / 7)
 m_Variable5 = CStr(CInt(m_Variable5) + 1)
 m_Variable5 = CStr(CInt(m_Variable5) * 7)

Can anyone explain why can't I use the first code, which is more destine for .Net platform?

Many thanks

Nadeem_MK
  • 7,533
  • 7
  • 50
  • 61
  • Please show a short but *complete* program demonstrating the problem. It certainly looks like it should work... – Jon Skeet Mar 13 '14 at 10:43
  • That's what bothering me, it should work.. Just add `Dim m_Variable5 as string = "325"` and debug the 3 lines, you'll see. – Nadeem_MK Mar 13 '14 at 10:51
  • Well I could do that, adding enough stuff around it to make it into a full program... and so could everyone else answering the question. Or you could do that work once, so that anyone who wants to can just copy, paste, compile, run. (Just a console app.) It shouldn't take long for you to do, but it's worth getting into the habit - it makes for a much better question if anyone trying to answer it can reproduce the issue in *seconds*. – Jon Skeet Mar 13 '14 at 11:03

1 Answers1

3

The reason of your exception is that after the execution of first line of your code m_Variable5 = "46.4285714285714" and it can't be converted to Int32 using Convert.ToInt32 function in the second line of your code.

In the second example it is converted, because you use CInt operator. CInt (when passed a string) performs more work than Convert.ToInt32. I, personally, prefer to use CInt.

Nadeem_MK
  • 7,533
  • 7
  • 50
  • 61
Sargis Koshkaryan
  • 1,012
  • 3
  • 9
  • 19
  • Yeah that has been tested as mentioned in the question itself. I want to know the explicit reason as to why Convert.ToInt32 throw the error! – Nadeem_MK Mar 13 '14 at 11:28
  • 2
    Accourding to MSDN , Convert.ToInt32 throws an exception, when input parameter does not consist of an optional sign followed by a sequence of digits (0 through 9). CInt function rounds the parameter to the closest even number. For example 3.5 rounds to 4. The explicit reason is in implementaion of Convert.ToInt32 and CInt. – Sargis Koshkaryan Mar 13 '14 at 11:35