Complete set: Intro to C - Bill Buchanan
Complete set: Intro to C - Bill Buchanan
Complete set: Intro to C - Bill Buchanan
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
5.3 Creating overloaded methods<br />
We can create overloaded methods ourselves very simply. We need only repeat the<br />
definition, but with a different parameter list.<br />
Care should be takes with this – it is considered good practice if each overloading<br />
performs essentially the same task. The MessageBox.Show is an excellent example<br />
of good practice (if rather excessive in have 12 options).<br />
• The same method can be used “quick‐and‐dirty” and “careful” users.<br />
• Sensible default values are given when parameters are left unspecified.<br />
During development of code we often find that we need <strong>to</strong> generalise. We start with<br />
a simple method and find that it needs <strong>to</strong> be more complex.<br />
The designers of MessageBox might have started with the notion of a simple alert<br />
box that <strong>to</strong>ok a single string – they then found that their users required more and<br />
more control.<br />
Using overloading it is possible <strong>to</strong> publish a simple component then expand on it.<br />
The advantage of this is that existing code that uses the simple interface does not<br />
have <strong>to</strong> be re‐written when the new version of the class is released.<br />
To avoid duplication of code we often have one “base” implementation that the others<br />
call. The based should be the “largest” overloading – the one with the most<br />
parameters.<br />
5.4 Overloaded Method Example<br />
The Country class records details of a single country – name, region, area, population<br />
and gdp.<br />
When the population increases (when a baby is born for example) we want <strong>to</strong> increment<br />
the population. The method <strong>to</strong> do this is called IncPop.<br />
duction <strong>to</strong> .NET<br />
<strong>Intro</strong><br />
Examples of the definition of an overloaded method<br />
public void IncPop(int increment)<br />
{<br />
this.population += increment;<br />
}<br />
public void IncPop()<br />
{<br />
IncPop(1);<br />
}<br />
Agilent .NET Course: Module 5, page 4