So I scribbled this post down on a piece of paper back in November or so, and going through my old stuff found it again today. At the time I had grandiose ideas of regularly blogging on random programming stuff, but I suppose that idea was abandoned in favour of irregularly blogging on random introspective stuff :P
Anyhow, this was back when I actually had to use VB (2005) for mech engg in Edmonchuck (dark days). I noticed this interesting thing:
Say you’ve got two combo boxes, A and B, and the value of A is “1″ and B is “2″.
Redim myArray(cboA.Text + cboB.Text - 1)
myArray.GetLength(0)
And you’ll get 12 for the array length.
But, like this:
Redim myArray(cboA.Text - 1 + cboB.Text)
myArray.GetLength(0)
You’ll get 3 for the array length.
Which totally violates the possibly-expected commutative property of add/subtract, because f(a + b – c) != f(a – c + b).
But, I guess what’s actually happening is that the “+” operator, when given String + String, simply appends the two strings together, thus “1″ + “2″ = “12″. Then, the String – Integer ends up being implicitly converted to Integer – Integer, so we get 12 – 1 = 11, and an array length of 12.
In the second case, the String – Integer ends up doing the same implicit type conversion on the String to make it Integer – Integer, so we get 1 – 1 + 2 = 2, and an array length of 3.
I guess it all boils down to VB being rather weakly typed. It’s progammer-friendly in that it doesn’t require a lot of typecasting, but also dangerous in that it gives you zero feedback on what it’s implicitly converting. In this case, I think I spent at least a few hours being super confused about some calculations messing up, before I realized my mistake.
Anyhow, that’s my random VB tale for today. C# ftw!
Tags: Code

No comments
Comments feed for this article
Trackback link: http://ethiessen.com/2008/07/16/weak-typing-in-vb/trackback/