Method Overloading

Methods of the same name can be declared in the same class, as long as they have different sets of parameters (determined by the number, types and order of the parameters). This is called method overloading. When an overloaded method is called, the C# compiler selects the appropriate method by examining the number, types and order of the arguments in the call. Method overloading is commonly used to create several methods with the same name that perform the same or similar tasks, but on different types or different numbers of arguments. For example, Math methods Min and Max (summarized in Section 7.3) are overloaded with 11 versions. These find the minimum and maximum, respectively, of two values of each of the 11 numeric simple types. Our next example demonstrates declaring and invoking overloaded methods. You will see examples of overloaded constructors in Chapter 9.

Declaring Overloaded Methods

In class MethodOverload (Fig. 7.13), we include two overloaded versions of a method called Squareone that calculates the square of an int (and returns an int) and one that calculates the square of a double (and returns a double). Although these methods have the same name and similar parameter lists and bodies, you can think of them simply as different methods. It may help to think of the method names as "Square of int" and "Square of double," respectively. When the application begins execution, class MethodOverloadTest's Main method (Fig. 7.14, lines 59) creates an object of class MethodOverload (line 7) and calls the object's TestOverloadedMethods method (line 8) to produce the application's output (Fig. 7.14).

Figure 7.13. Overloaded method declarations.

 1 // Fig. 7.13: MethodOverload.cs
 2 // Overloaded method declarations.
 3 using System;
 5 public class MethodOverload
 6 {
 7 // test overloaded square methods
 8 public void TestOverloadedMethods()
 9 {
10 Console.WriteLine( "Square of integer 7 is {0}", Square( 7 ) );
11 Console.WriteLine( "Square of double 7.5 is {0}", Square( 7.5 ) );
12 } // end method TestOverloadedMethods
13 14 // square method with int argument 15 public int Square( int intValue ) 16 { 17 Console.WriteLine( "Called square with int argument: {0}", 18 intValue ); 19 return intValue * intValue; 20 } // end method Square with int argument 21 22 // square method with double argument 23 public double Square( double doubleValue ) 24 { 25 Console.WriteLine( "Called square with double argument: {0}", 26 doubleValue ); 27 return doubleValue * doubleValue; 28 } // end method Square with double argument 29 } // end class MethodOverload

Figure 7.14. Application to test class MethodOverload.

(This item is displayed on page 302 in the print version)

 1 // Fig. 7.14: MethodOverloadTest.cs
 2 // Application to test class MethodOverload.
 3 public class MethodOverloadTest
 4 {
 5 public static void Main( string[] args )
 6 {
 7 MethodOverload methodOverload = new MethodOverload();
 8 methodOverload.TestOverloadedMethods();
 9 } // end Main
10 } // end class MethodOverloadTest
Called square with int argument: 7
Square of integer 7 is 49
Called square with double argument: 7.5
Square of double 7.5 is 56.25

In Fig. 7.13, line 10 invokes method Square with the argument 7. Literal integer values are treated as type int, so the method call in line 10 invokes the version of Square at lines 1520 that specifies an int parameter. Similarly, line 11 invokes method Square with the argument 7.5. Literal real number values are treated as type double, so the method call in line 11 invokes the version of Square at lines 2328 that specifies a double parameter. Each method first outputs a line of text to prove that the proper method was called in each case.

Notice that the overloaded methods in Fig. 7.13 perform the same calculation, but with two different types. C#'s new generics feature provides a mechanism for writing a single "generic method" that can perform the same tasks as an entire set of overloaded methods. We discuss generic methods in Chapter 26.

Distinguishing Between Overloaded Methods

The compiler distinguishes overloaded methods by their signaturea combination of the method's name, and the number, types and order of its parameters. The signature also includes the way those parameters are passed, which can be modified by the ref and out keywords that we discuss in Section 7.14. If the compiler looked only at method names during compilation, the code in Fig. 7.13 would be ambiguousthe compiler would not know how to distinguish between the two Square methods (lines 1520 and 2328). Internally, the compiler uses signatures to determine whether the methods in a class are unique in that class.

For example, in Fig. 7.13, the compiler will use the method signatures to distinguish between the "Square of int" method (the Square method that specifies an int parameter) and the "Square of double" method (the Square method that specifies a double parameter). If Method1's declaration begins as

void Method1( int a, float b )

then that method will have a different signature than the method declared beginning with

void Method1( float a, int b )

The order of the parameter types is importantthe compiler considers the preceding two Method1 headers to be distinct.

Return Types of Overloaded Methods

In discussing the logical names of methods used by the compiler, we did not mention the return types of the methods. This is because method calls cannot be distinguished by return type. The application in Fig. 7.15 illustrates the compiler errors generated when two methods have the same signature, but different return types. Overloaded methods can have the same or different return types if the methods have different parameter lists. Also, overloaded methods need not have the same number of parameters.

Figure 7.15. Overloaded methods with identical signatures cause compilation errors, even if return types are different.

 1 // Fig. 7.15: MethodOverload.cs
 2 // Overloaded methods with identical signatures
 3 // cause compilation errors, even if return types are different.
 4 public class MethodOverloadError
 5 {
 6 // declaration of method Square with int argument
 7 public int Square( int x )
 8 {
 9 return x * x;
10 }
12 // second declaration of method Square with int argument
13 // causes compilation error even though return types are different
14 public double Square( int y )
15 {
16 return y * y;
17 }
18 } // end class MethodOverloadError

Common Programming Error 7 10

Declaring overloaded methods with identical parameter lists is a compilation error regardless of whether the return types are different.



    Introduction to Computers, the Internet and Visual C#

    Introduction to the Visual C# 2005 Express Edition IDE

    Introduction to C# Applications

    Introduction to Classes and Objects

    Control Statements: Part 1

    Control Statements: Part 2

    Methods: A Deeper Look


    Classes and Objects: A Deeper Look

    Object-Oriented Programming: Inheritance

    Polymorphism, Interfaces & Operator Overloading

    Exception Handling

    Graphical User Interface Concepts: Part 1

    Graphical User Interface Concepts: Part 2


    Strings, Characters and Regular Expressions

    Graphics and Multimedia

    Files and Streams

    Extensible Markup Language (XML)

    Database, SQL and ADO.NET

    ASP.NET 2.0, Web Forms and Web Controls

    Web Services

    Networking: Streams-Based Sockets and Datagrams

    Searching and Sorting

    Data Structures



    Appendix A. Operator Precedence Chart

    Appendix B. Number Systems

    Appendix C. Using the Visual Studio 2005 Debugger

    Appendix D. ASCII Character Set

    Appendix E. Unicode®

    Appendix F. Introduction to XHTML: Part 1

    Appendix G. Introduction to XHTML: Part 2

    Appendix H. HTML/XHTML Special Characters

    Appendix I. HTML/XHTML Colors

    Appendix J. ATM Case Study Code

    Appendix K. UML 2: Additional Diagram Types

    Appendix L. Simple Types


    Visual C# How to Program
    Visual C# 2005 How to Program (2nd Edition)
    ISBN: 0131525239
    EAN: 2147483647
    Year: 2004
    Pages: 600

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: