And the Visual Basic Type Is....

Continuing on my last very simplistic blog post, I thought I'd show something seemingly even more basic. While the following is simple from our perspective, I imagine the coding done by Microsoft on the back-end to make this simple was much more challenging.

Continuing on my last very simplistic blog post, I thought I'd show something seemingly even more basic. While the following is simple from our perspective, I imagine the coding done by Microsoft on the back-end to make this simple was much more challenging.

Consider a scaled down version of the Visual Basic 10 listing I created in my last blog post:

Module Module1

Sub Main()

Dim scores() AsInteger = {10, 20, 30, 40}

Console.WriteLine(scores.GetType)

EndSub

EndModule

Let me ask you a simple question. What is the type of the scores array? It should be obvious that it is an Integer. What, however, is the type of the scores() array if we change the third line to the following:

Module Module1

Sub Main()

Dim scores()= {10, 20, 30, 40}

Console.WriteLine(scores.GetType)

EndSub

EndModule

The answer is no longer clear. In fact, the answer is different if you are using Visual Basic "10" instead of an earlier version. In Visual Basic 2005/8, the answer would be that it is an array of type System.Object. In Visual Basic 10, it would actually be of type Integer still.

The type is inferred in Visual Basic "10". If I change the line to the following, the type will again change:

Dim scores()= {10, 20, 30, 40, 3.14}

Because a number with a decimal place has been added, in Visual Basic "10" the type will now be inferred to be Double.

Making one more change, what would the type of scores be for the following?

Dim scores()= {10, 20, 30, 40, "Now what?" }

If you guessed string, you'd be wrong. At this point, there are too many possibilities from the type of array that scores could be to start guessing. As such, scores falls back to being of type System.Object.

This, of course, is how the pre-beta works. Chances are this will make it into the final release. This is one more way that Visual Basic provides great ease-of-use functionality. It is also one more way that Visual Basic can help you shoot yourself in the foot.