Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top