Seeing Polymorphism in Action
Let’s look at a simple example of polymorphism before getting into some game code. The little project PolymorphismExample comes with the source code for this book. This do-nothing project contains a single form. On this form are one textbox, one button, one label, one radio button, and one checkbox control. The name for each control is the default name given to it by Visual Studio when it was placed on the form. The Click event for all five controls is the same event handler:
Private Sub SomethingClick(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles RadioButton1.Click, _
Button1.Click, CheckBox1.Click, Label1.Click, TextBox1.Click
Debug.WriteLine(sender.ToString)
End Sub
As with most event handlers, the object being acted upon is passed in as the first parameter in the variable named sender, which is of type Object. This is the root ancestor class for every other class in the .NET Framework and every class you create yourself (in other words, every class is a descendant of the Object class).The lone line of code in this event handler calls the ToString method on the passed-in sender variable, and the result of this method is written to the Visual Studio .NET debugger window. If you were to run this program and click each of the five controls one time, you would see the following output in the debugger window:
System.Windows.Forms.Button, Text: Button1
System.Windows.Forms.Label, Text: Label1
System.Windows.Forms.TextBox, Text: TextBox1
System.Windows.Forms.CheckBox, CheckState: 1
System.Windows.Forms.RadioButton, Checked: True
As you can see, the job of the ToString method is to output the class name of the control and a little piece of information about the control itself. In the case of the button, label, and textbox, the Text property of the control outputs. In the case of the checkbox, the CheckState property displays, and in the case of the radio button, the Checked property displays.The polymorphic behavior is that the sender variable can point to any one of the five controls attached to this event handler, but it doesn’t need to know which control it points to in order to call the ToString method on each of them, even though the implementation of the ToString method might be totally different. You could, for example, create some crazy control that opens an Internet connection and downloads a string from across the globe to use as the output of its ToString method, but you could invoke this method using the same Click event handler that the other controls use.