<< Chapter < Page | Chapter >> Page > |
The two methods named Equals are defined as overloaded methods in the Object class. (They have the same name and different formal argument lists.)
Some of these methods are intended to be overridden for various purposes. This includes GetHashCode , and ToString .
However, some of the methods, such as GetType are intended to be used as is without overriding.
From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in C#:
I will begin the discussion of polymorphism with method overloading, which is the simplest of the three. I will cover method overloading in this module andwill cover polymorphism based on overridden methods using class inheritance and interface inheritance in future modules.
C# allows you to have two or more method definitions in the same scope with the same name, provided that they have different formal argument lists. This ismethod overloading .
Some authors refer to method overloading as a form of compile-time polymorphism , as distinguished from run-time polymorphism . This distinction comes from the fact that, for each method call, the compiler determines whichmethod (from a group of overloaded methods) will be executed. This decision is made when the program is compiled.
In contrast, with method overriding, the determination of which overridden method to execute isn't made until runtime.
In practice, with overloaded methods, the compiler simply examines the types, number, and order of the parameters being passed in a method call and selectsthe overloaded method having a matching formal argument list.
In these modules on polymorphism, I will explain sample programs that are as short and as simple as I know howto make them, while still illustrating the important points regarding polymorphism. My objective is to make the polymorphicconcepts as clear as possible without having those concepts clouded by other programming issues.
Because of their simplicity, these programs aren't likely to resemble problems that you will encounter in the real world. I will simply ask you totrust me when I tell you that polymorphism has enormous application in real world programming.
I will explain a sample program named Polymorph01 to illustrate method overloading. A complete listing of the program is provided in Listing 4 near the end of the module.
Method overloading can occur both within a class definition, and vertically within the class inheritance hierarchy.
In other words, an overloaded method can be inherited into a class that defines other overloaded versions of the method.
The program named Polymorph01 illustrates both aspects of method overloading.
Notification Switch
Would you like to follow the 'Xna game studio' conversation and receive update notifications?