Link to home
Start Free TrialLog in
Avatar of Norma Posy
Norma PosyFlag for United States of America

asked on

Integer to String conversion

Using VB6:

I recently discussed this issue under a different question.
See: “VB automatically overrides my capitalization”

Briefly: I made the mistake of naming a variable with a reserved name;
Dim sTR As String.

Str() is a VB function that returns a number as a string.
So, where I had Str(), VB re-capitalized it as sTR (throughout the entire project), and the function stopped working. (Simply returns a blank.)

I renamed my variable, but the Str function stayed broken.
I saved and exited. The next day, upon reload, all the references to Str() were capitalized correctly. And they all worked.

EXCEPT for the specific subroutine where I had initially goofed. In this procedure (only),
sString = Str(iInteger) returned a blank, “”.

Three observations and related questions:

sString = iInteger makes the conversion without invoking the Str() function at all.
Question: Is this good programming practice?
 If VB does this, why bother with the Str() function at all?

sString = CStr(iInteger) works just fine.
Question: is CStr() preferable to Str()?
Seems redundant.

I presume the function Str$() exists for back-compatibility with older versions of Basic
(like Quick Basic).
Question: Is the “$” no longer necessary?



SOLUTION
Avatar of zorvek (Kevin Jones)
zorvek (Kevin Jones)
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>Question: is CStr() preferable to Str()?

No. See the above.

Kevin
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>sString = iInteger is not considered good practice as it is an implicit data conversion which potentially could cause data loss, if option strict was set to on in your project this line would be shown as an error.

There can be no data loss. The operation will either succeed if the string can be converted or fail of the string cannot be converted. And failure will occur with:

   sString = iInteger

with the same scenarios as with:

   sString = CStr(iInteger)

Kevin
Maybe data loss would not occur in this scenario shown, I was talking generally why it is not a good idea to have implicit data conversions.
Avatar of Norma Posy

ASKER

Thank you all.