CHAPTER 4 CORE C# PROGRAMMING CONSTRUCTS, PART II
' VB6 code examples.
Public Function AddInts(ByVal x As Integer, ByVal y As Integer) As Integer
AddInts = x + y
End Function
Public Function AddDoubles(ByVal x As Double, ByVal y As Double) As Double
AddDoubles = x + y
End Function
Public Function AddLongs(ByVal x As Long, ByVal y As Long) As Long
AddLongs = x + y
End Function
Not only can code such as this become tough to maintain, but the caller must now be painfully
aware of the name of each method. Using overloading, you are able to allow the caller to call a single
method named Add(). Again, the key is to ensure that each version of the method has a distinct set of
arguments (methods differing only by return type are not unique enough).
Note As explained in Chapter 9, it is possible to build generic methods that take the concept of overloading to
the next level. Using generics, you can define type placeholders for a method implementation that are specified
at the time you invoke the member in question.
To check this out firsthand, create a new Console Application project named MethodOverloading.
Now, consider the following class definition:
// C# code.
class Program
{
static void Main(string[] args)
{
}
// Overloaded Add() method.
static int Add(int x, int y)
{ return x + y; }
static double Add(double x, double y)
{ return x + y; }
static long Add(long x, long y)
{ return x + y; }
}
The caller can now simply invoke Add() with the required arguments and the compiler is happy to
comply, given the fact that the compiler is able to resolve the correct implementation to invoke given the
provided arguments:
131