This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

C# Method Overloading

The sixth article in the C# Object-Oriented Programming tutorial explains method overloading. This technique permits multiple methods to be declared using the same name but with different parameters. Method overloading is our first look at polymorphism.

Automatic Type Conversion

In the example above, a second variant of the method was created because we wanted to square a double and this could not be implicitly cast to an integer. However, where an implicit cast is possible, the compiler will perform this conversion automatically. In the following example, the Main method is updated to use a float. As you can see, because no overloaded method exists specifically for floats the double variation is used instead.

static void Main(string[] args)
    float squareMe = 5;


Double Square calculated


Return Type Limitations

The signature defines the name and the set of parameters for the method. In order to use overloaded methods, the signature must differ for each method declaration. This means that every overloaded method in a class must have either a different number of parameters or a different set of argument data types to every other method with the same name. However, the return type of the method is not included in this signature. This means that two methods that differ only in return type cannot be created in the same class. For this reason, the following code is invalid and so will not compile:

class Calculate
    public static int Square(double number)
        return (int)(number * number);

    public static double Square(double number)
        return number * number;

A Note on Reference Parameters

Where parameters are passed by reference, they are considered to be different to those passed by value. This means that it is valid to have an overloaded method with the same set of parameter data types if one version passes parameters by value and the other by reference.

21 October 2007