Explicitly Assign Type From Dictionary

The AI that I use to help me with Xojo coding prefers that I explicitly assign a type whenever recovering data from a Dictionary so:

Var boatLength As Integer = someDictionary.Value(“Length”).IntegerValue

rather than simply

Var boatLength As Integer = someDictionary.Value(“Length”)

It argues that Dictionary values are Variants and it is better, for some reason, to use the more verbose line of code.

Is this something that experienced human developers do? Or is this just a quirk of Gemini.

I do it because it helps my brain understand what values I’m passing around and, though I’m not sure, may be faster than relying on framework type conversion.

1 Like

There are two reasons to do this:

  1. It allows you to lean on the compiler’s type checking. If you expect an integer and assign it to a string, the code will compile and will even “work” but the format of the string is undefined. Other conversions will “work” too, such as reading a boolean into an integer. But you’re better off being explicit of your types so that should something change, you can catch it.
  2. When passing variants to a method, explicit typing allows the compiler to know which overloaded signature is the desired one. You might have Constructor(InitialValue As String) and Constructor(InitialValue As Integer) and passing as a variant will cause a compile error because it’s impossible to know which one you meant.

Overall, it’s a good habit to get into. Variants make your code harder to maintain, but are a necessary evil.

5 Likes