This article is the first of a two part series that explains how data type conversion - that is, "casting" - happens in VB.NET both at the level of your source code and deeper down - the way things actually happen in memory. Part Two explains more about the three casting operators, including how fast they can perform the same casting.
Why Casting?
The usual reason is that some operation you need for your program just won't work without a specific data type. For example, suppose you want to store both elements from a web page and numeric elements taken from a file in the same array. The problem is that arrays aren't flexible enough to allow this. To make it work, you have to "cast" all of the elements into a common type. (Probably String.)
(Real World Example: As I was writing this article, a reader asked a question that involved implicit conversion from a String found on a web page. It turned out that there was no direct conversion possible because the web page encoding was unknown to VB.NET. See Using Numbers from a Web Page in a VB program.)
Here's an example where casting is required using one of Microsoft's latest technologies, WPF.
Suppose you want the same Windows Forms subroutine to handle multiple events. You can do that by placing all of the events in a Handles clause in the Sub statement:
Private Sub myEventSub_Click( ... ) _
Handles Control1.Click, Control2.Click ... etc.
But WPF's more complex event handling model requires a different technique. Multiple controls in a WPF logical control tree can all trigger the same event. So you need to extract the control you need from the WPF RoutedEventArgs parameter - in this case, it's the familiar "e" parameter that you see in all event subroutines - passed to the event subroutine. (Don't worry if you don't understand any of this. The point is only to show that casting is a technique that you need no matter what VB.NET technology you're using.) To get that information, you can cast e to a local control declared in your subroutine.
In more detail, suppose you have a StackPanel with a lot of Button controls inside of it. You want the same event subroutine to handle all of the Buttons.
<StackPanel ButtonBase.Click="StackPanel_Click">
<Button x:Name="Button1" />
<Button x:Name="Button2" />
<Button x:Name="Button3" />
</StackPanel>
You can cast e to a Button object to get the result you want. CType is the casting function used here:
Private Sub StackPanel_Click( _
ByVal sender As System.Object, _
ByVal e As System.Windows.RoutedEventArgs)
Dim myButton As Button = CType(e.Source, Button)
Console.WriteLine(myButton.Name)
End Sub
In general, when a VB.NET statement requires one type but you have another type instead, casting is the solution.
