Question on .ToString and Variant data types

I was working through the programming book and hit a section on variants.

Originally it was showing that variants first = 123 and second = “456” became “123456” string when added together third = first + second

I was trying to apply .ToInteger and .ToString to force it to treat as integer.

Do variant data types always default to string when combined?

[Code] var first, second, third as Variant
var v as Integer

first=123
second=“456”
third = first + second.ToInteger
MessageBox(third.ToString) [/Code]

If I remove the ToString/Integer portions I get 12345, but I get errors if I add them.

Heh, and apparently a follow up question, how do I properly show code? :sweat_smile:

Do variant data types always default to string when combined?

No, they will default to whatever their original type was when added. You should check out the Variant page in the documentation. You can use VarType(myVariant) or myVariant.Type to determine the type of the value stored within a Variant. Some values can be converted to other types, some cannot. If you don’t know what’s there, make sure to do some error handling with Try…Catch.

Have a look here: [CODE] Tag is missing in Toolbar or?

Select the lines with code and apply the </> button.

var first, second, third as Variant
var v as Integer

first=123
second=“456”
third = first + second.ToInteger
MessageBox(third.ToString)

and you don’t need [code][/code].

I don’t think so. The variant will change to fit the data that you’re putting in, e.g. the following changes it from an original type of Int32 to a String.

dim a as variant = 123
'a is an int32 here
a = a + "456"
'a is now a string

What I think Kevin is looking for is:

Dim a As Variant = 123
'a is an int32 here
a = a + "456"
'a is now a string

Dim b As Variant = "456"
a = 123 + b.Int32Value 'or you could use IntegerValue if you want to keep with Integer
'a is still an Int32
1 Like

I guess I should’ve said:

Thanks for explaining.

And just to make sure I get it right, when you concatenate the Int32 and a String, that’s a form of casting.

@TimStreater Thanks for Code pasting tip! --Kevin

I suspect it may also be that a blank line before/after the lines-to-be-code is needed but I’m not 100% certain of that. That button seems to apply backticks to a bit of in-line code but some kind of indenting for multiple lines.

Forum for Xojo Programming Language and IDE. Copyright © 2021 Xojo, Inc.