O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Overloading

When we define more than one member in a type with the same name (be it a constructor or, as we’ll see later, a method) we call this overloading.

Initially, we created two constructors (two overloads of the constructor) for PolarPoint3D, and they compiled just fine. This is because they took different sets of parameters. One took three doubles, the other two. In fact, there was also the third, hidden constructor that took no parameters at all. All three constructors took different numbers of parameters, meaning there’s no ambiguity about which constructor we want when we initialize a new PolarPoint3D.

The constructor in Example 3-31 seems different: the two doubles have different names. Unfortunately, this doesn’t matter to the C# compiler—it only looks at the types of the parameters, and the order in which they are declared. It does not use names for disambiguation. This should hardly be surprising, because we’re not required to provide argument names when we call methods or constructors. If we add the overload in Example 3-31, it’s not clear what new PolarPoint3D(0, 0) would mean, and that’s why we get an error—we’ve got two members with the same name (PolarPoint3D—the constructor), and exactly the same parameter types, in the same order.

Looking at overloaded functions will emphasize that it really is only the method name and the parameters that matter—a function’s return type is not considered to be a disambiguating aspect of the member for overload purposes.

That means ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required