Lesson 2: Overloading Members

Lesson 2: Overloading Members

Overloading allows you to create multiple members with the same name. Each member that shares a name must have a different signature. Overloading is most commonly used in methods, but Visual C# allows you to overload operators as well. In this lesson, you will learn how to create overloaded members.

After this lesson, you will be able to

  • Explain how to create an overloaded method

  • Describe how to create an overloaded operator in Visual C#

Estimated lesson time: 15 minutes

You might want to create a member that can accept different sets of parameters. Take the following method as an example:

Visual Basic .NET

Public Sub Display(ByVal DisplayValue As Integer) ' Implementation Omitted End Sub

Visual C#

public void Display(int DisplayValue) { // Implementation omitted }

This method is perfectly acceptable on its own. But suppose you want to allow the client to designate a duration parameter for the method if needed? Or perhaps you would like the method to be able to accept an integer or a string as the DisplayValue parameter. Visual Basic .NET allows you to designate optional parameters, but this functionality is unavailable in Visual C#. Furthermore, optional parameters do not address the second situation where a method needs to accept arguments that could be of multiple types.

The solution is to provide overloads. Overloads are multiple methods with the same name. Overloaded methods must have different signatures, but need not have the same return type or access level. When an overloaded method is called, the common language runtime examines the types of the arguments supplied in a method call. It then matches the argument list with the available overload signatures and calls the one that fits. If no overload fits the types of arguments that are supplied, an error results.

Member methods are the most commonly overloaded member type. You can create overloaded methods in both Visual Basic .NET and Visual C#. Visual C# allows you to overload operators, thereby providing custom operator functionality for user-defined types.

Creating Overloading Methods

You can create an overloaded method in the same way you would create any other method: by declaring the method with a name, an access level, a return type, and an argument list. An overloaded method must have the same name as a preexisting method, but must have a different signature. Access level and return type can be the same or different. The following code sample demonstrates an overloaded method:

Visual Basic .NET

' This example demonstrates an overloaded method. Public Sub DisplayMessage(ByVal I As Integer) MessageBox.Show(I.ToString()) End Sub ' This method has the same name as the previous method, but is ' distinguishable by signature Public Sub DisplayMessage(ByVal S As String) MessageBox.Show(S) End Sub

Visual C#

// This example demonstrates an overloaded method. public void DisplayMessage(int I) { MessageBox.Show(I.ToString()); } // This method has the same name as the previous method, but is // distinguishable by signature public void DisplayMessage(string S) { MessageBox.Show(S); }

Two methods are defined, each with the same name but with different signatures and a separate implementation. When a method with the name DisplayMessage is called, the runtime examines the argument type supplied to it. If a String is provided, the method that takes a String is called. If an Integer is provided, the method that takes an Integer is called.

To create an overloaded method

  1. Declare a method that has the same name as an existing method. This method must have a signature that differs from any preexisting methods of the same name. The access level and return type can be the same or different from other methods of the same name.

  2. Provide an implementation for the newly declared method.

Overloading Operators with Visual C#

When working with user-defined types, it is sometimes convenient to define arithmetic, logical, or comparison operators that can operate with these types. Take for example the following struct:

Visual C#

public struct HoursWorked { float RegularHours; float OvertimeHours; }

This simple struct might be used in an accounting application to keep track of the number of regular hours and the number of overtime hours an employee works. But working with multiple instances of this struct can prove difficult. For instance, suppose you want to add two instances together. You would have to create a new method specifically to add the instances. If you want to add more than two instances, you would have to call this method multiple times. Visual C# allows you to define operator behaviors for user-defined types. To enable the use of the addition operator with your struct, for example, you would overload the + operator and implement the appropriate behavior.

To create an overloaded operator, use the operator keyword with the following basic syntax:

Visual C#

public static type operator op (Argument1[, Argument2]) { implementation }

The type component of the syntax represents the type that this operator acts on and returns. Argument1 and Argument2 represent the arguments that the operator takes. For a unary operator, there will be only one argument, and it must be of the same type as type. For a binary operator, there will be two arguments, and at least one must be the same type as type. Op represents the operator itself, such as +, -, >, !=, and so on. An overloaded operator must be public so that clients working with your user-defined type can access it. An overloaded operator must also be static. The definition for an overloaded operator must occur within the user-defined type that it is to act upon. Although these examples use structs, you can define overloaded operators for both structs and classes there is no difference in the way they are defined. The following example demonstrates creating an overloaded + operator for the previously defined HoursWorked struct:

Visual C#

public struct HoursWorked { float RegularHours; float OvertimeHours; // The overloaded operator must occur within the class // it acts upon public static HoursWorked operator + (HoursWorked a, HoursWorked b) { HoursWorked Result = new HoursWorked(); Result.RegularHours = a.RegularHours + b.RegularHours; Result.OvertimeHours = a.OvertimeHours + b.OvertimeHours; return Result; } }

Once the overloaded operator is defined, you can use it in code just as you would any other operator. The following example demonstrates code that adds together two instances of the HoursWorked struct:

Visual C#

// This example assumes that the variables Sunday and Monday // represent instances of the HoursWorked struct that have been // created and had appropriate values set. HoursWorked total = new HoursWorked(); total = Sunday + Monday;

As with overloaded methods, you can create several additional implementations of overloaded operators as long as they differ in signature. To extend the example of the HoursWorked struct, you might want to add an Integer to the NormalHours field using the + operator. You can create an additional overload of the + operator to carry out this task. An example follows:

Visual C#

public struct HoursWorked { float RegularHours; float OvertimeHours; // This is the overloaded operator defined in the // previous example public static HoursWorked operator + (HoursWorked a, HoursWorked b) { HoursWorked Result = new HoursWorked(); Result.RegularHours = a.RegularHours + b.RegularHours; Result.OvertimeHours = a.OvertimeHours + b.OvertimeHours; return Result; } // An additional implementation of the + operator is // defined below. public static HoursWorked operator + (HoursWorked a, int b) { HoursWorked Result = new HoursWorked(); Result.RegularHours = a.RegularHours + b; return Result; } }

To create an overloaded operator with Visual C#

  1. Declare the overloaded operator within the class or struct that it is to act upon. Use the operator keyword to signify that it is an operator, followed by the operator that you want to overload. Overloaded operators must be public and static. If the operator is a binary operator, at least one of the arguments must be of the same type that it returns.

  2. Provide an appropriate implementation for the operator.

Lesson Summary

  • Overloading allows you to create multiple methods with the same name but different implementations. Overloaded methods must differ in signature but can have the same or different return types and access levels. You declare overloaded methods just as you would declare a regular method.

  • Visual C# allows you to define custom behaviors for operators when used with user-defined types. Overloaded operators must be public and static. You use the operator keyword to declare an overloaded operator.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net