3.3 Method-Overloading
Objectives
Learn what overloading is
Learn why we need overloading
Write some overloaded methods
Discussion
Overloading allows the programmer to define several methods with the same name, as long as they take a different set of parameters.
File Location
Right click on your solution
Go to Add > New Project and select Console App (.NET Framework)
Name it
MethodOverloading
Example
An example would be a program that has different attack parameters. With the example below, the player can do an attack with no parameters, one parameter for attackPoints
, or two parameters of attackPoints
and weaponName
. The compiler will choose which one to use based on what fits. Add the code in your Program.cs
file:
Base Method
Overloaded method with 1 parameter
Overloaded method with 2 parameters
One More Example
Base Method
Overloaded method with one parameter
Overloaded method with two parameters
Overloaded method with five parameters
Discussion
In this example we have 4 different AnnounceGreatMusic()
methods and we used overloading to make this happen. You can see we have different parameters for each of the AnnounceGreatMusic()
methods. When the program runs, it will check to see what parameters it has and check to see if any of your AnnounceGreatMusic(
) methods match those parameters. In our Main()
method above, we assigned some different parameters to the methods to test it out.
Challenge
Make a few different addition methods within a math class and use overloading to take in different parameters.
Next: Constructors
Last updated