Casting

Why does

Dim s As String = CType("abcdefg", String).ConvertEncodings(Encodings.Ascii)

work, while

Dim s As String = String("abcdefg").ConvertEncodings(Encodings.Ascii)

doesn’t?

Hmm, that smells like a bug. I bet @npalardy knows however…

yeah but the explanation is long and not really easy
its far easier with things like Integers that are not, at their heart, reference types (strings are an immutable reference type under the hood)

CType is an explicit conversion of a value to a given type
And it will do all the same conversions that simply assigning a value of one type to a variable of a different type will - like assigning an integer to a double. It quite literally “creates” a result that IS the type you pyt in the CType call
SO the first one quite literally returns a string - to which you can apply the ConvertEncoding extension method

The second, a cast. is semantically different
Its operation is to take a set of “bytes” and tells the runtime to now treat those bytes as whatever the cast type was. But in the case of the text literal “abcdefg” it is a type that this doesnt work on. “abcdefg” is a "text literal and a string cast doesnt work (you cant cast one to the other) And so when you compile you get

Window1.Open, line 1
Type mismatch error. Expected String, but got TextLiteral
Dim s As String = String(“abcdefg”).ConvertEncodings(Encodings.Ascii)

Could it work ? I suppose IF they had a compiler engineer which … well … :frowning:

Thanks, Norm. Is there really any reason then to use Type(variable) instead of CType(Variable, Type)?

I do miss things like

Dim s as String = "abcdefg".Left(4)

that I could do in VB.NET (i.e. methods on literals)

I would have thought that if the desire was there that Xojo could implement that without a compiler engineer. I suspect it depends on the code generator that passes your typed code to the compiler. You could parse "abcd.Left(4)" in the editor, determine that "abcd" is a String literal and rewite the code behind the scenes to Left("abcd", 4).

I personally love languages that treat literals as objects (e.g: Ruby or my own scripting language - Roo) but ultimately that’s not how Xojo is designed.

Yes there are still uses for Cast vs CType
A cast is “treat the bits as this other type” - no conversion. So you can take a Uint and cast it to a signed int of the same size and vice versa

Dim s as String = “abcdefg”.Left(4)
Thats this feedback case http://feedback.xojo.com/case/56629

“1234” is a text literal - not a “string” and the extension methods apply to strings. Without some compiler tweaks I doubt Xojo can make that work since “text literal” is not any type that can be extended